Created
November 29, 2021 11:07
-
-
Save charlypoly/ad1512f69db626d7f9608e0b3cd42806 to your computer and use it in GitHub Desktop.
TypeScript type guard usage
This file contains hidden or 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
function isPremiumUser(user: User): user is PremiumUser { | |
return user.plan === 'premium' | |
} | |
function getPremiumOptions(user: User | PremiumUser): PremiumOptions | null { | |
if (isPremiumUser(user)) { | |
user | |
// `user` is of type `PremiumUser` | |
return user.premiumOptions | |
} else { | |
user | |
// `user` is of type `User` | |
return null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment