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
Incorrect narrowing when a type guard returns a type union #41871
classAnimal{privatex: number=0;}classCatextendsAnimal{publicwhiskers: number=1;}classBroom{privatey: number=1;publicwhiskers: number=1;publichandle: number=3;}functionhasWhiskers(input: Animal|Broom): input is Cat|Broom{returninputinstanceofCat||inputinstanceofBroom;}functionincorrect(input: Animal|Broom): number{if(hasWhiskers(input)){// INCORRECT: There should be a compiler error here, // but `input` got incorrectly narrowed to `Broom` // (instead of `Cat | Broom`)returninput.handle;}return-1;}functioncorrect(input: Animal|Broom): number{if(inputinstanceofCat||inputinstanceofBroom){// CORRECT: `handle` is not a member of `Cat | Broom`,// so the compiler correctly reports an error here.returninput.handle;}return-1;}constcat=newCat();// Prints "undefined" because cat.handle didn't actually existconsole.log(incorrect(cat));
But it can also be reproduced using simpler interface inheritance, like this:
interfaceAnimal{legs: number;}interfaceCatextendsAnimal{whiskers: number;}interfaceBroom{whiskers: number;handle: number;}functionhasWhiskers(input: Animal|Broom): input is Cat|Broom{returnObject.hasOwnProperty.call(input,'whiskers');}functionincorrect(input: Animal|Broom): number{if(hasWhiskers(input)){// INCORRECT: There should be a compiler error here, // but `input` got incorrectly narrowed to `Broom` // (instead of `Cat | Broom`)returninput.handle;}return-1;}
Expected behavior:
One would expect identical type narrowing when extracting this:
functionhasWhiskers(input: Animal|Broom): input is Cat|Broom{returninputinstanceofCat||inputinstanceofBroom;}...functionf(input: Animal|Broom): number {if(hasWhiskers(input)){...
Actual behavior:
The type is incorrectly narrowed to Broom instead of Cat | Broom.
As a result, clearly incorrect code compiles without any error.
Activity
andrewbranch commentedon Dec 8, 2020
This is indeed a duplicate of #31156.
typescript-bot commentedon Dec 10, 2020
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.