telvis
Version:
Typescript/Javascript safe-navigation operator, also known as Elvis operator
38 lines (26 loc) • 1.19 kB
Markdown
Typescript/Javascript safe navigation
This library adds a `path` method to the `Object` prototype which allows you to safely get a nested property of an object.
This is comparable to the elvis operator `?.` (Swift, C
`a.path("b").path("c").path("d")` will return `a.b.c.d` if `a`, `b` and `c` and not `null` or `undefined`, and otherwise will return `undefined`.
This can also be shortened to `a.path("b","c","d")`
Note: Requires Typescript 2.1 because it uses the `keyof` operator
`npm install telvis --save`
In your files: (**WIP**)
Sorry, still working out the modules
```
interface A { b ?: B }
interface B { c ?: C }
interface C { hello ?: string }
let a1: A = { b : { hello: "world" }}
let a2: A = { b : {} }
// world will be of type string | undefined and at runtime will contain "world"
let world = a1.path("b", "hello")
// noworld will be of type string | undefined and at runtime will contain undefined
let noworld = a2.path("b", "hello")
// This will not compile, as "nonexistent" is not a key in A
// let invalid = a1.path("nonexistent")
```