Skip to content

O (Option)

type None = { readonly _tag: 0 }
type Some<A> = { readonly _tag: 1; readonly value: A }
type Option<A> = None | Some<A>

Numeric _tag for fast branching. none is a singleton.

some<A>(value: A): Option<A>
none: None
fromNullable<A>(value: A | null | undefined): Option<NonNullable<A>>
fromPredicate<A, B extends A>(pred: (value: A) => value is B): (value: A) => Option<B>
fromPredicate<A>(pred: (value: A) => boolean): (value: A) => Option<A>

A type-guard predicate narrows the Some value; a plain predicate does not.

map<A, B>(f: (a: A) => B): (o: Option<A>) => Option<B>
flatMap<A, B>(f: (a: A) => Option<B>): (o: Option<A>) => Option<B>
filter<A>(pred: (value: A) => boolean): (option: Option<A>) => Option<A>
tap<A>(f: (a: A) => void): (o: Option<A>) => Option<A>

filter also preserves type-guard narrowing. Its runtime behavior is unchanged: a matching Some passes through and a failed predicate produces the none singleton.

getOrElse<B>(onNone: () => B): <A>(o: Option<A>) => A | B
getOrThrow<A>(option: Option<A>): A
getOrThrow(onNone: () => unknown): <A>(option: Option<A>) => A
match<A, B, C>({ none: () => B, some: (a: A) => C }): (o: Option<A>) => B | C
toNullable<A>(o: Option<A>): A | null
toUndefined<A>(o: Option<A>): A | undefined
toResult<E>(onNone: () => E): <A>(o: Option<A>) => Result<A, E>
isSome<A>(o: Option<A>): o is Some<A>
isNone<A>(o: Option<A>): o is None
import { pipe } from '@stopcock/fp'
import * as O from '@stopcock/fp/option'
// safe env variable with validation
const port = pipe(
O.fromNullable(process.env.PORT),
O.map((s) => parseInt(s, 10)),
O.filter((n) => n > 0 && n < 65536),
O.getOrElse(() => 3000),
)
const directPort = O.fromPredicate((port: number) => port > 0 && port < 65536)(3000)
// chain nullable lookups
pipe(
O.fromNullable(user.address),
O.flatMap((a) => O.fromNullable(a.zip)),
O.match({
none: () => 'no zip',
some: (zip) => zip,
}),
)
// convert to Result for error context
pipe(
O.fromNullable(headers.authorization),
O.toResult(() => 'missing auth header'),
)