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
allow storing results of narrowing of class properties in booleans for further narrowing #53267
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.
Activity
fatcerberus commentedon Mar 15, 2023
This seems intentional and is not specific to classes:
testNumberis notreadonly.MartinJohns commentedon Mar 15, 2023
Bruce Pascoe (@fatcerberus) But even if you make it
readonlyit's not working.RyanCavanaugh commentedon Mar 17, 2023
It does need to be
readonly. Looks like we have a bug here when the property is onthisspecifically, since this code works as expected:Common source of bug here when we check for something being an
Identifier, whichthisisn't. From a type perspective these examples are the same so it's probably a simple fix.