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 :)
pet.swim!== undefined then it must be a Fish. But in order for TypeScript to allow you to access theswimproperty onpet, you need to assertpettype as Fish.asas meaning an assertion that the value has a certain type, in which case that assertion is a lie (assuming the programmer understands that it isn't true). Or you can interpret it as a request for the compiler to not type-check the expression it occurs in, and a request cannot be a lie. A formalist might interpret it as having no meaning except for what the compiler does with it.(pet as Fish), there is a good chance thatpetwill not actually be aFish.