You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
constcall=(f: ()=>void)=>f();consttest=()=>{leta: undefined|number=undefined;// Typescript seems to be completely unaware that the value// of `a` can change in the following call.call(()=>{a=1;});// And there, it still think that `a` can only// possibly be `undefined`.if(a!==undefined){// this line get rejecteda.toString();}};
🙁 Actual behavior
It seems that Typescript is not considering a function call to affect local variable. It proceed to narrow the type from this limitation, and thus reject valid code.
Not assigning undefined to a causes the error to disappear BUT this is still a problem, because I might want a default value here (could be a number initially, that later get changed to undefined for example).
Note: Typescript is aware that the value of a can change in a synchronous IIFE
const test = () => {
let a: undefined | number = undefined;
// Typescript is aware that the value of `a` can change in a synchronous IIFE
(() => { a = 1; })();
a; // number
};
test();
Craig P Hicks (@craigphicks) Yes, IIFEs are special-cased: since the compiler can readily see from the syntax that the function will always be called immediately (and exactly once), it's treated the same as if the code was written inline.
Activity
MartinJohns commentedon Mar 21, 2024
Another duplicate of #9998.
fjolliton commentedon Mar 21, 2024
Is there anything to prevent to narrow such types? (a configuration option or a directive to put somewhere)
MartinJohns commentedon Mar 21, 2024
No. It's all written in that issue. You can use a type assertion to prevent the initial narrowing:
42 as undefined | number.craigphicks commentedon Mar 23, 2024
Note: Typescript is aware that the value of
acan change in a synchronous IIFEfatcerberus commentedon Mar 23, 2024
Craig P Hicks (@craigphicks) Yes, IIFEs are special-cased: since the compiler can readily see from the syntax that the function will always be called immediately (and exactly once), it's treated the same as if the code was written inline.
typescript-bot commentedon Mar 26, 2024
This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes.