Last active
December 10, 2021 10:04
-
-
Save charlypoly/4b11a6885395602bf9c5bcb06a42db56 to your computer and use it in GitHub Desktop.
TypeScript Discriminated Unions
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
type UUID = string; | |
interface BasicUser { | |
id: UUID; | |
first_name: string; | |
last_name: string; | |
} | |
interface User extends BasicUser { | |
plan: 'free' | |
} | |
interface PremiumOptions { | |
option1: string | |
// ... | |
} | |
interface PremiumUser extends BasicUser { | |
plan: 'premium' | |
premiumOptions: { | |
option1: string | |
} | |
} | |
let user : PremiumUser | User | undefined | |
if (user && user.plan === "premium") { | |
user | |
// `user` is of type `PremiumUser` | |
} else { | |
user | |
// `user` is of type `User` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should be: