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
classUtils{staticisDefined<T>(value: T): value is NonNullable<T>{returnvalue!=null;};}classA{publictestNumber: number|undefined;constructor(){constisNumber=Utils.isDefined(this.testNumber);if(isNumber){// Type 'number | undefined' is not assignable to type 'number'constx: number=this.testNumber;}}}functionfoo(x: number|undefined){constisNum=Utils.isDefined(x);if(isNum){// Works. No error hereconsty: number=x;}}
🙁 Actual behavior
The narrowed type of class property is not inferred if narrowing result stored in variable
This seems intentional and is not specific to classes:
Narrowing through indirect references occurs only when the conditional expression or discriminant property access is declared in a const variable declaration with no type annotation, and the reference being narrowed is a const variable, a readonly property, or a parameter for which there are no assignments in the function body.
It does need to be readonly. Looks like we have a bug here when the property is on this specifically, since this code works as expected:
classUtils{staticisDefined<T>(value: T): value is NonNullable<T>{returnvalue!=null;};}classA{publicreadonlytestNumber: number|undefined;foo(){constobj: this =this;constisNumber=Utils.isDefined(obj.testNumber);if(isNumber){// okconstx: number=obj.testNumber;}}}
Common source of bug here when we check for something being an Identifier, which this isn't. From a type perspective these examples are the same so it's probably a simple fix.
Bug Report
🔎 Search Terms
https://www.google.com/search?q=typescript+does+not+narrow+type+of+stored+variable&oq=typescript+does+not+narrow+type+of+stored+variable&aqs=chrome..69i57j69i64.8615j0j7&sourceid=chrome&ie=UTF-8
🕗 Version & Regression Information
⏯ Playground Link
Playground link with relevant code
💻 Code
🙁 Actual behavior
The narrowed type of class property is not inferred if narrowing result stored in variable
I expect the type to be correctly inferred as it's working for regular variables inside a function
This PR fixed this bug for functions
The text was updated successfully, but these errors were encountered: