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
Search Terms:
assignable type guards
assignable type guard return value
assign type guard to variable
Code
interfaceA{type: 'A';aProperty: string;}interfaceB{type: 'B';bProperty: number;}typeAorB=A|B;functionisA(obj: AorB): obj is A{returnobj.type==='A';}consto={type: 'A',aProperty: 'value'}asanyasAorB;// this should be an error, and it isconsole.log(o.aProperty);// this should work, and it doesif(isA(o)){console.log(o.aProperty);}// this example discards the type guard information, but it // ought to set oIsA to type (o is A), and apply the type// guard inside the if statement. constoIsA=isA(o);if(oIsA){console.log(o.aProperty);}
Expected behavior: oIsA should have the type returned by the type guard function. if (oIsA) ... should narrow the type of o within the if block.
Actual behavior: oIsA is a regular boolean value. The type guard function can only be used directly within a conditional block.
I can't find the other duplicates, but we only check syntactically whether isA is a user-defined type guard at the if check (and other syntactic locations). The type predicate return type is really just a boolean in any other context. So oIsA doesn't track any information about the type of o itself.
We've considered this problem, but it seems fairly complex and expensive to solve in a general way.
DanielRosenwasser
changed the title
Assignable type guards
Type predicate results stored in variables don't narrow guarded types
Mar 5, 2018
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.
TypeScript Version: 2.8.0-dev.20180222
Search Terms:
assignable type guards
assignable type guard return value
assign type guard to variable
Code
Expected behavior:
oIsA
should have the type returned by the type guard function.if (oIsA)
... should narrow the type ofo
within the if block.Actual behavior:
oIsA
is a regular boolean value. The type guard function can only be used directly within a conditional block.Playground Link:
https://goo.gl/6Pk5vr
Related Issues:
The text was updated successfully, but these errors were encountered: