Created
March 1, 2021 16:13
-
-
Save florianpasteur/ed619ab703108b01c9c120672789ce3c to your computer and use it in GitHub Desktop.
Null-safe Optional with Typescript
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
// 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>, optionalKeyedUserInfo: OptionalUser) { | |
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'. | |
} | |
} | |
// V2: with specific key for the value | |
// In this example `user` | |
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