Skip to content

Instantly share code, notes, and snippets.

@charlypoly
Last active December 10, 2021 10:04
Show Gist options
  • Save charlypoly/4b11a6885395602bf9c5bcb06a42db56 to your computer and use it in GitHub Desktop.
Save charlypoly/4b11a6885395602bf9c5bcb06a42db56 to your computer and use it in GitHub Desktop.
TypeScript Discriminated Unions
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`
}
@fabb
Copy link

fabb commented Dec 10, 2021

Should be:

interface User extends BasicUser {
   plan: 'free'
}

@charlypoly
Copy link
Author

@fabb true point!

Fixed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment