TypeScript · Senior · Question 41 of 75

Is the narrowing of a let variable preserved inside a callback?

function f(x: string | number) {
  if (typeof x === 'string') {
    setTimeout(() => x.toUpperCase());
  }
}

Explanation

Previously, inside a callback TS assumed x might be reassigned and reset the narrowing to string | number. Since 5.4, the compiler understands the value is stable after the last assignment and keeps the narrowing. For const it already worked before.

Further reading

Problem with a question

TypeScript · Senior · question 41

Test yourself

Take the TypeScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz