Reputation:
I begin with Typescript and I tried to use an object inside the if
block. In the if
I test for the condition - if one property exists and if it's the case I can use it into the if
block but TS compiler don't seems to understand
type Fish = {
swim: () => void
}
type Bird = {
fly: () => void
}
const test = function (pet: Fish | Bird) {
if ((pet as Fish).swim) {
pet.swim()
}
}
Upvotes: 0
Views: 65
Reputation: 370619
The check
if ((pet as Fish).swim)
does nothing to help TS infer the type of pet
, because every Fish has swim
already. Use in
to check if the property exists instead, and do it on the pet
, so that pet
gets narrowed down to Fish
and can have swim
called on it:
const test = function (pet: Fish | Bird) {
if ('swim' in pet) {
pet.swim();
}
};
Upvotes: 1