Created
January 2, 2017 23:23
-
-
Save dooman87/8bcf86421ed4dda76dce5a1145a4b984 to your computer and use it in GitHub Desktop.
Advanced type guards.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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