Skip to content

Instantly share code, notes, and snippets.

@xiel
Last active July 8, 2019 11:14
Show Gist options
  • Save xiel/4ee047f04412ffacba5c2c2c0e9400ed to your computer and use it in GitHub Desktop.
Save xiel/4ee047f04412ffacba5c2c2c0e9400ed to your computer and use it in GitHub Desktop.
Optional Chaning in Typescript
/**
* 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