Skip to content

Instantly share code, notes, and snippets.

@florianpasteur
Last active March 16, 2021 09:34
Show Gist options
  • Save florianpasteur/d8810ac88e2f11a535de668ed6ad0b95 to your computer and use it in GitHub Desktop.
Save florianpasteur/d8810ac88e2f11a535de668ed6ad0b95 to your computer and use it in GitHub Desktop.
Typescript Optional
// Example type
type UserInfo = {
username: string,
email: string
};
type Present<T> = {
exists: true,
value: T
};
type Absent = {exists: false};
type Optional<T> = Present<T> | Absent;
function dealWithOptionals(optionalUserInfo: Optional<UserInfo>) {
if (optionalUserInfo.exists) {
// Can access value
optionalUserInfo.value
} else {
// Can not access value
// optionalUserInfo.value // TS2339: Property 'value' does not exist on type 'Optional<UserInfo>'.   Property 'value' does not exist on type 'Absent'.
}
}
type OptionalWithKey<T, K extends {[k: string] : T}> = {
exists: true,
} & K | Absent
type OptionalUser = OptionalWithKey<UserInfo, {user: UserInfo}>;
function dealWithOptionalKeyedUser(optionalKeyedUserInfo: OptionalUser) {
if (optionalKeyedUserInfo.exists) {
// Can access user
optionalKeyedUserInfo.user
} else {
// Can not access user
// optionalKeyedUserInfo.user // TS2339: Property 'user' does not exist on type 'OptionalWithKey<UserInfo, { user: UserInfo; }>'.   Property 'user' does not exist on type 'Absent'.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment