telvis
v0.2.1
Published
Typescript/Javascript safe-navigation operator, also known as Elvis operator
Downloads
15
Maintainers
Readme
Telvis
Typescript/Javascript safe navigation
About
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#) or monadic options like Option.flatMap
(Scala) or Maybe.#>>
(Haskell)
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
Installation
npm install telvis --save
In your files: (WIP) Sorry, still working out the modules
Examples
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")