TS 5.4 has a feature called “Preserved Narrowing in Closures Following Last Assignments”, but it says,
Note that narrowing analysis doesn’t kick in if the variable is
assigned anywhere in a nested function. This is because there’s no way
to know for sure whether the function will be called later.
It gives the following code to explain that,
function printValueLater(value: string | undefined) {
if (value === undefined) {
value = "missing!";
}
setTimeout(() => {
// Modifying 'value', even in a way that shouldn't affect
// its type, will invalidate type refinements in closures.
value = value;
}, 500);
setTimeout(() => {
console.log(value.toUpperCase());
// ~~~~~
// error! 'value' is possibly 'undefined'.
}, 1000);
}
But I find that even if I don’t do the assignment, e.g. comment out that assignment call I still get “error! ‘value’ is possibly ‘undefined’.” Why is that ?
function printValueLater(value: string | undefined) {
if (value === undefined) {
value = "missing!";
}
setTimeout(() => {
console.log(value.toUpperCase());
// ~~~~~
// I still get 'value' is possibly 'undefined'.
}, 1000);
}