-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Type guard fails to narrow union type #1802
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Worth noting that this compiles fine, which is inconsistent: function logType4(animal?: Cat) {
if (animal instanceof Cat) {
console.log("Cat");
}
} Since |
What exactly are you trying to accomplish by putting |
@danquirk in my code there's a callback function that I am not in control of, which can return a value of one of 2 types or nothing (undefined). I'm trying to determine what type was returned by the function and I'm hitting this issue as a result. It looks more like this: interface AnimalOrNothing {
(): Dog | Cat | void;
}
var getAnimal: AnimalOrNothing = () => {
if (Math.random() > 0.5) {
return new Dog();
}
else if (Math.random() > 0.5) {
return new Cat();
}
else {
return;
}
}
var unknown = getAnimal();
if (unknown instanceof Dog) {
unknown.bark();
}
else if (unknown instanceof Cat) {
unknown.pur();
}
else {
} Note that I don't have control over the method that can either return a value or nothing. |
Since |
With the fix in #1803, the |
Isn't 'void' implicit in any type? interface AnimalOrNothing {
(): string | number;
}
var getAnimal: AnimalOrNothing = () => {
if (Math.random() > 0.5) {
return new Dog();
}
else if (Math.random() > 0.5) {
return new Cat();
}
else {
return; // allowed already!
}
}
var unknown = getAnimal();
if (unknown instanceof Dog) {
unknown.bark();
}
else if (unknown instanceof Cat) {
unknown.pur();
}
else {
unknown // should narrow to void
}
// Or alternative
if (unknown == null) {
unknown // narrows to void
}
else if (unknown instanceof Cat) {
unknown.pur();
}
else {
unknown.bark();
} |
This works, AS EXPECTED:
This doesn't work, which is debatable since
undefined instanceof Cat
is legal JS but I prefer the type warning since it catches errors:This doesn't work, but I would definitely expect it to:
See playground for code.
As it stands, if a union type contains void, I don't know how to use
instanceof
with it.The text was updated successfully, but these errors were encountered: