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
{{ message }}
Repository navigation
Type narrowing not preserved in closure between narrowing and usage before last assignment (incomplete "Preserved Narrowing in Closures Following Last Assignments") #57405
This behaviour happens in the latest 5.0.4-beta and nightly.
I'm not sure if this is a bug, intended behaviour or a missing feature. To me, this looks like incomplete type narrowing in closures before the last assignment, when it should be trivial to narrow the type.
functionuseNumber(x: number){returntrue}functiontestBroken(foobar: number|undefined){letcheckedFoobar: number|undefinedconstfn=()=>{constisNumber=checkedFoobar!==undefinedconsttmp=isNumber&&useNumber(checkedFoobar)// error; because `checkedFoobar` is `number | undefined`// If this line is commented out, the error goes away in 5.4.0// (Before 5.4.0 the error always exists, even without this assignment)checkedFoobar=foobar}returnfn}
🙁 Actual behavior
In the sample above:
constisNumber=checkedFoobar!==undefinedconsttmp=isNumber&&useNumber(checkedFoobar)// error; because `checkedFoobar` is `number | undefined`
🙂 Expected behavior
TypeScript should know that checkedFoobar is number (and keep that knowledge in the isNumber variable).
There's no assignment between the check and the usage, so any type narrowing should hold.
In the sample above:
constisNumber=checkedFoobar!==undefinedconsttmp=isNumber&&useNumber(checkedFoobar)// works; because `checkedFoobar` should be `number`
Additional information about the issue
An ugly workaround is to repeat the undefined check directly in the condition:
consttmp=checkedFoobar!==undefined&&useNumber(checkedFoobar)// works; because `checkedFoobar` is `number`
Activity