I was reading the official Typescript documentation and came across this example in the type predicate section:
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
I think I understand type predicates, but don't understand the pet as Fish1
part. In this code snippet, isn't the programmer lying to typescript just to get the predicate to work? It seems to me the isFish
function that returns the predicate is telling typescript "this is a Fish" so that it won't throw a TypeError
because the so-called Fish
isn't guaranteed to have a swim
method. Is this understanding correct :)