Created
November 29, 2021 11:03
-
-
Save charlypoly/b312eb49ecd06d857626a924bd6e5585 to your computer and use it in GitHub Desktop.
TypeScript type guards
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
type UUID = string; | |
interface User { | |
id: UUID; | |
first_name: string; | |
last_name: string; | |
plan: 'free' | 'premium' | |
} | |
interface PremiumOptions { | |
option1: string | |
// ... | |
} | |
interface PremiumUser extends User { | |
plan: 'premium' | |
premiumOptions: { | |
option1: string | |
} | |
} | |
function getPremiumOptions(user: User | PremiumUser): PremiumOptions | null { | |
return user.plan === 'premium' ? (user as PremiumUser).premiumOptions : null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment