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
classBird{fly(){}}classFish{swim(){}}functionmoveAnimal(animal: Bird|Fish){if(animalinstanceofBird){// type is narrowed down to Bird => OKanimal.fly();}else{// type is narrowed down to Fish => WRONGanimal.swim();}}moveAnimal({fly(){}});
Expected behavior:
Parameter animal should still be of type Bird | Fish in the else case.
Actual behavior:
Type is narrowed to Fish which leads to an error if called with a parameter of a type that is structurally compatible with Bird | Fish but is neither an instance of the Bird or Fish class. This seems to be related to some other issues related to the nominal typing of instanceof in combination with TypeScript's structural typing.
The text was updated successfully, but these errors were encountered:
You can add a private field to each class to prevent this.
In general people either fall into the camp of "Only use new and instanceof works" or "Sometimes use object literals and don't use instanceof". We don't have syntax for determining which camp you want to be in for each particular class and don't intend to add it.
Is a special syntax even necessary? The animal parameter could be left as Bird | Fish in the else case. According to #1719 this should already be the case (until it changed since version 1.4).
Nearly everyone would consider that behavior to be a bug. Evidence from the linked issue is that no code in the real world does an instanceof check and then doesn't assume the other member of the union in the else branch
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.4.0
Code
Expected behavior:
Parameter
animal
should still be of typeBird | Fish
in theelse
case.Actual behavior:
Type is narrowed to
Fish
which leads to an error if called with a parameter of a type that is structurally compatible withBird | Fish
but is neither an instance of theBird
orFish
class. This seems to be related to some other issues related to the nominal typing ofinstanceof
in combination with TypeScript's structural typing.The text was updated successfully, but these errors were encountered: