Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save charlypoly/ad1512f69db626d7f9608e0b3cd42806 to your computer and use it in GitHub Desktop.
Save charlypoly/ad1512f69db626d7f9608e0b3cd42806 to your computer and use it in GitHub Desktop.
TypeScript type guard usage
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