option.ts
Option ~Monad for typescript
option.ts
can be used with either javascript or typescript.
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
Importing the library
Here's everything that can be imported from option.ts
:
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.
If you already know the value is defined for sure (not nullable) or not, you can create a Some
or None
directly:
Option.all(...optionsOrValues)
Creates a new Option holding the tuple of all the passed values if they were all Some or non null/undefined values,
else returns None
// some === Some([10, 20, 5]) // none === None
None
The Option constant representing no value.
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 is guaranteed to never contain a null or undefined value.
// some === Some(66)
flatMap
Maps the value contained in this Some to a new Option, else returns None.
// some === Some(44)
filter
If this Option is a Some and the predicate returns true, keep that Some. In all other cases, return None.
// some === Some(33)
orElse
Returns this Option unless it's a None, in which case the provided alternative is returned.
// some === Some(33)
match
Returns the result of calling Some(value)
if this is a Some, else returns the result of calling `None()``
// result === '20'
Misc
get
Some
instances return their value, whereas None
always return undefined
.
Thus, this method never throws.
// value === 33
isDefined
Returns whether this Option has a defined value (i.e, it's a Some(value))
Note: this refines the type of the Option to be a Some so it's guaranteed its value is not null/undefined.
getOrElse
Returns this Option's value if it's a Some, else return the provided alternative
// value === 33
forEach
Applies the given procedure to the option's value, if it is non empty.
Option33.forEachconsole.logx