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
First of all I'm sorry if I get the jargon wrong, I'm new to typescript (I tried to search for this issue and failed, I may have used the wrong search terms).
When using type guards, code in an else block uses the condition in the if to infer the type of the variable. However if the if contains an early return the rest of the function should be treated as the else of the if from we we returned.
Code
// A self-contained demonstration of the problem follows...typeFoo={a: string};functionisFoo(x): x is Foo{returnx&&typeof(x.a)==='string';}typeBar={b: string};functionbuz1(arg: Foo|Bar) : string{if(isFoo(arg))returnarg.a;// OK arg inferred to be Fooelsereturnarg.b;// OK arg inferred to be Bar}functionbuz2(arg: Foo|Bar) : string{if(isFoo(arg))returnarg.a;// OK arg inferred to be Fooreturnarg.b;// ** Error b isn't a member of Foo|Bar **}
Expected behavior:
function buz2 should compile with no error. Actual behavior:
Error when accessing member b of arg even though arg can be inferred to be of type Bar (as it is in buz1.else).
The text was updated successfully, but these errors were encountered:
Hey @lanzkron I believe this will be fixed in TypeScript 2.0 where we'll start using control flow analysis for types. Give the nightlies a try out with npm install -g typescript@next and see how it works!
Version 1.8
When using type guards, code in an
else
block uses the condition in theif
to infer the type of the variable. However if theif
contains an earlyreturn
the rest of the function should be treated as theelse
of theif
from we we returned.Code
Expected behavior:
function
buz2
should compile with no error.Actual behavior:
Error when accessing member
b
ofarg
even thougharg
can be inferred to be of typeBar
(as it is inbuz1.else
).The text was updated successfully, but these errors were encountered: