Last active
July 8, 2019 11:14
-
-
Save xiel/4ee047f04412ffacba5c2c2c0e9400ed to your computer and use it in GitHub Desktop.
Optional Chaning in 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
/** | |
* Optional Chaining in Typescript | |
* lets you safely access nested properties, while preserving type information | |
* | |
* Usage: | |
* type TData = { foo: Optional<{ bar: Optional<number> }> } | |
* const data: TData = { foo: undefined } | |
* const num = optionalChain(() => data.foo!.bar) | |
*/ | |
type Optional<T> = T | undefined | |
export function optionalChain<T extends () => unknown>(getValue: T): Optional<ReturnType<T>> | |
export function optionalChain(getValue: () => unknown) { | |
let value | |
try { | |
value = getValue() | |
} catch (e) {} | |
return value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment