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
exportinterfaceK9{variant: 'DOG'|'WOLF';bark: ()=>void;}exportinterfaceFeline{variant: 'CAT'|'LION';meow: ()=>void;}exporttypeCatOrDog=K9|Feline;letinstance={}asanyas(K9|Feline)if(instance.variant==='DOG'||instance.variant==='WOLF'){instance.bark();//works}if(instance.variant!=='DOG'&&instance.variant!=='WOLF'){letx=instance.variant;//correct type inferredinstance.meow()//should work but doesn't}
Expected behavior:
The first condition check should be able to infer that we are dealing with a Feline.
The reason it doesn't work as originally written is that when instance.variant !== 'DOG' is applied to the original declaration of K9, no narrowing is performed (because variant could still be 'WOLF'). Likewise, instance.variant !== 'WOLF' doesn't by itself narrow instance. However, when K9 is declared as a union type we can individually narrow.
So, it's working as intended, but you could argue it is a design limitation.
TypeScript Version: v3.5.1
Search Terms:
discriminated unions, !==
Code
Expected behavior:
The first condition check should be able to infer that we are dealing with a Feline.
Actual behavior:
It is unable to discriminate.
Playground Link: playground link
Related Issues: #27541
The text was updated successfully, but these errors were encountered: