type predicate

// โญ๏ธ 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