Closed
Description
TypeScript Version: 2.7.0
Search Terms:
typeof union narrowing properties
Code
interface Bird {
fly: () => any;
layEggs: () => any;
}
interface Fish {
swim: () => any;
layEggs: () => any;
}
function Move(pet: Fish | Bird) {
if (pet.swim) {
pet.swim();
} else {
pet.fly();
}
if (typeof pet.swim === "function") {
pet.swim();
} else {
pet.fly();
}
if ("swim" in pet) {
pet.swim();
} else {
pet.fly();
}
}
Expected behavior:
I expect the code above to work without any errors at all. I feel it's all reasonable.
Actual behavior:
I get an error for the first 2 if/else branches, where I am accessing the property swim
. The last branch works fine. I'm aware of the possibility of having a user-defined type guard function, but I don't want to have to do that.
Related Issues:
Couldn't find any