Hi, I'm reading through the TS docs and I'm currently at the Type Predicates section.
As an example they have this snippet:
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
And my question is if the function isFish and isFish2 have the same functionality in the next snippet, and if not, why? Both console.log work.
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function getSmallPet(): Fish | Bird {
return Math.random() >= 0.5 ? {swim() {}} : {fly() {}}
}
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
function isFish2(pet: Fish | Bird): boolean {
return "swim" in pet
}
const pet = getSmallPet()
if (isFish(pet)) console.log("is Fish according to isFish")
if (isFish2(pet)) console.log("is also Fish according to isFish1")
I'm having a hard time understanding the use case for type predicates, they just seem unnecessarily verbose to me when isFish2 does the same (I think), with less code.