Examples in the documentation showcase the is
predicate and the in
operator for this purpose.
is
predicate:
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
if (isFish(pet)) {
pet.swim();
}
else {
pet.fly();
}
in
operator:
function move(pet: Fish | Bird) {
if ("swim" in pet) {
return pet.swim();
}
return pet.fly();
}
The usage of the in
operator appears to be more concise, yet extracting type differentiation into a function like the is
predicate enhances readability and maintenance in the long term.
Are there any instances where the is
predicate can effectively differentiate between types when compared to the in
operator?