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
TypeScript Version: 3.7.5, also tested on 3.9.0-dev.20200212
Search Terms: equals, type guard, type parameter, narrowing
Code
typeAorB='a'|'b';functionisA(t: AorB): t is 'a'{returnt==='a';}functiontest<TextendsAorB>(arg: T){if(isA(arg)){leta1: T&'a'=arg;// ok}if(arg==='a'){leta2: T&'a'=arg;// error}}
Expected behavior: The condition arg === 'a' should narrow the type of arg to T & 'a' in the second if block, in the same way as the equivalent type guard function does.
Actual behavior: The type of arg is not narrowed in the second if block.
As I assume what is happening here is that the condition is valid, as it has no error-prone runtime effect, but the typeguard is not applied by it. And the reason why the condition doesn't work as typguard is a fact that typeguard can work only forall members. Below equivalent typeguard:
functionguard<XextendsAorB,YextendsAorB>(x: X,y: Y): x is Y{returnx==y}// error
It means that conditions behave as typeguards only if left and right side of the condition overlap.
And here we can have situation when provided type doesn't overlap (X can be 'a', Y can be 'b').
Is this assumption correct? I cannot find any information about that in language specification.
TypeScript Version: 3.7.5, also tested on 3.9.0-dev.20200212
Search Terms: equals, type guard, type parameter, narrowing
Code
Expected behavior: The condition
arg === 'a'
should narrow the type ofarg
toT & 'a'
in the secondif
block, in the same way as the equivalent type guard function does.Actual behavior: The type of
arg
is not narrowed in the secondif
block.Playground Link: Playground Link
Related Issues: N/A
The text was updated successfully, but these errors were encountered: