Skip to content

Instantly share code, notes, and snippets.

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