0

I have a retry util that takes a function as an argument. This retry util defines a variable in the scope.

let code: number;

retry(() => {
  code = 123;
});

const msg = `Your code is: ${code}!`;
console.log('msg:', msg);

function retry(cb: () => void) {
  cb();
}

Typescript underlines code with error:

Variable 'code' is used before being assigned.(2454)

Because it doesn't know that cb got ran. Is it possible to type up retry such that TS knows the cb argument ran? So it applies the type affects of that argument?

Noitidart
  • 35,443
  • 37
  • 154
  • 323

1 Answers1

0

What you can do is tell the compiler that you are sure this variable was assigned to a value, like this:

let code: number;

retry(() => {
  code = 123;
});

const msg = `Your code is: ${code!}!`;
console.log('msg:', msg);

function retry(cb: () => void) {
  cb();
}

See this post for more information on the "!" operator

Togira
  • 355
  • 3
  • 11