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());
}
}- ✓Correct answer: Yes, since TS 5.4, if the variable isn't reassigned afterwards
- 2No, never: narrowing is always reset in closures
- 3Yes, but only for
constvariables in any version
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.