typed-option
Library for working with Option
s in a type safe manner.
tl;dr
Option
s makes working with, potentially, undefined
values more concise and easy to read.
Example
Given the function:
: string | undefined { if Math > 05 return x return undefined}
Turn something like this:
let result = 'FAILED'const a = // a is string | undefinedif a const b = // b is string | undefined if b const c = // c is string | undefined if c result = c // c is string console
Into this:
const result2 = Option // v is of type string. // v is of type string. // v is of type string. console
Intro
An Option
is either of type Some
or None
.
- Some - represents a value of something (a defined value)
- None - represents a value of nothing (an undefined value)
In the example above, we start with a Some('SUCCESS')
. Then we apply the function canFailFn
multiple times to the value of our Some
. If the computation fails at any point, we are returned a None
.
With Options, you do not need to know if you have a Some
or None
when applying functions. Only when you need the result do you have to deal with the potential None
case. This is typically done by calling the .getOrElse
function (as seen above).
Unions with undefined
One thing to note is that undefined
is removed from union types:
interface Foo a?: numberconst myFoo: Foo = a: 5myFooa // 'number | undefined`'const fooOption = Option // Option<number>fooOption // typeof a is number
This means that you will not have to worry about manually testing for undefined
. A Some
will never contain an undefined
value.
Functions
Explanation
Option.from
gives you a None
for undefined
values and a Some
for defined
values.
Option // Some(true)Option // Some(false)Option // Some({})Option // Some(0)Option // Some('')Option // None
You can also pass an additional predicate of what a legal value is.
Option // Some(false)Option // NoneOption // None
do
run a fn to a Option if it is of type Some
. Similar to map
, but does not alter the Option.
// logs: 'world' // logs nothing
map
apply fn to a Option if it is of type Some
// Some('Hello, world') // None
flatMap
Same as map, but for when your fn
returns a Option. flatMap
will remove the nested option.
: Option<string>const option = ... // Some('Hello, Option')option.map(getOptionFn) // Some(Some('Hello, Option'))option.flatMap(getOptionFn) // Some('Hello, Option')
getOrElse
get the value from a Some
or return the else
value for a None
// 1 // 999 // 1 // 999
orElse
is the same as getOrElse
, but else
returns a Option
// Some(1) // Some(999)
filter
gives a predicate that a Some
must hold. If not, returns None
// None() // Some(100) // None()
match
gives a pattern matching
syntax way to modify a Option. Usefull for when you only care if the Option is of type Some
// a Some(1) // a none
isNone
tests if the given Option
is of type None
,
isSome
tests if the given Option
is of type Some
const opt1 = ...ifopt1 // opt1 is None in this blockifopt1 // opt1 is Some in this block