muerwre.github.io/content/Typescript/Type guards.md
2022-11-03 10:38:11 +06:00

277 B

Useful for type checking at compile and run time:

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

Usage:

const pet = getSmallPet();
 
if (isFish(pet)) {
  pet.swim();
} else {
  pet.fly();
}