Optional chaining implementation in TypeScript.
Uses option type
Requirement
This library requires TS 2.8+ version to use conditional type
Install
npm install optional-chain
Usage
; ; // { name: null };optionalUser.k"name".k"first".get; // undefined, does not throw an exception.
API
optional-chain
library exports below APIs.
optional
optional
is a fuctory function to creates a Option
instance.
Option<T>
An instance of Option
can be constructed with a value for the souce of T
. Option
class can hold a type of Some
or None
based on given source.
.k(name: string)
; ; ;;optionalUser.k"name"; // Option<string>optionalUser.k"sns"; // Option<{twitter: { username: string }}>optionalUser.k"sns".k"facebook"; // NoneoptionalUser.k"foo"; // compile error
Returns a Option<T>
narrowed by specified property of Object.
.i(index: number)
Returns a Option<T>
narrowed by specified index of Array. If index is not in array, this returns Option<undefined>
.
optionalUser .k"followers" .i0 .k"name"; // None
.get()
Returns a value of Option
.
optionalUser.k"name".get; // yayoc
.match({ some: T => any, none: T => any })
A public method of Option
to do pattern matching.
If target Option
is Some
type, this funciton returns a result of given some
function. Otherwise, this function returns a result of given none
function.
optionalUser .k"sns" .k"twitter" .match; // @yayoc_
.getOrElse(value: any)
A public method to return T
value when the instance contains some value. Otherwise, this function will return given value.
optionalUser .k"sns" .k"facebook" .k"url" .getOrElse"https://facebook.com"; // https://facebook.com
Credits
This library is highly inspired by lens.ts
@utatti created.