option.ts
Option ~Monad for typescript
option.ts
can be used with either javascript or typescript 2.0.
This Option wrapper is mostly meant to be used at call sites, where you want to create and transform optional value expressions.
The advantage of only using it there, is that you keep neat, non wrapped JSON structures as your data.
API
Creating an Option
Option(x)
Creates an Option from a value.
If the value is null or undefined, it will create a None, else a Some.
const some = Option(33)
const none = Option(null)
Option.all(...optionsOrValues, transform)
Creates a new Option holding the computation of the passed Options if they were all Some or plain defined instances,
else returns None
const some = Option.all(
Option(10), 20, Option(5),
(a, b, c) => a + b + c
)
const none = Option.all(
Option(10), None, Option(5),
(a, b, c) => a + b + c
)
None
The Option constant representing no value.
Note: Some
can not be imported as it would result in unsafe Option creations (e.g Some containing null/undefined).
Instead, use Option(myValue)
.
import { None } from 'option.ts'
Transforming an Option
map
Maps the value contained in this Some, else returns None.
Depending on the map function return value, a Some could be tranformed into a None, as a Some will never contain a null or undefined value.
const some = Option(33).map(x => x * 2)
flatMap
Maps the value contained in this Some to a new Option, else returns None.
const some = Option(33).flatMap(_ => Option(44))
filter
If this Option is a Some and the predicate returns true, keep that Some.
In all other cases, return None.
const some = Option(33).filter(x => x > 32)
orElse
Returns this Option unless it's a None, in which case the provided alternative is returned.
const some = Option(null).orElse(() => Option(33))
Misc
Accessing the underlying value of the Option
Options are simple functions, call it to access the underlying value.
Some
instances return their value, whereas None
returns undefined
const value = Option(33)()
isDefined
Returns whether this Option has a defined value (i.e, it's a Some(value))
getOrElse
Returns this Option's value if it's a Some, else return the provided alternative
const value = Option(undefined).getOrElse(33)