type predicate
this-based type guards (
this is ยซTยป
)
// โญ๏ธ type predicate: ยซparamยป is ยซTยป
// ยซparamยป : parameter name of current function
// ยซTยป : a type
// โญ type predicate โฎ โญ๏ธ
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
// both calls to 'swim' and 'fly' are now okay.
let pet = getPet();
if (isFish(pet)) pet.swim();
else pet.fly();
Last updated
Was this helpful?