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