Skip to content

Instantly share code, notes, and snippets.

@dooman87
Created January 2, 2017 23:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dooman87/8bcf86421ed4dda76dce5a1145a4b984 to your computer and use it in GitHub Desktop.
Save dooman87/8bcf86421ed4dda76dce5a1145a4b984 to your computer and use it in GitHub Desktop.
Advanced type guards.
interface Bird {
fly();
layEggs();
}
interface Fish {
swim();
layEggs();
}
function isFish(pet: Fish | Bird): pet is Fish {
return (<Fish>pet).swim !== undefined;
}
...
// Both calls to 'swim' and 'fly' are now okay.
if (isFish(pet)) {
pet.swim();
}
else {
pet.fly();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment