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.
Constructors
Section titled “Constructors”some<A>(value: A): Option<A>none: NonefromNullable<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.
Transforms
Section titled “Transforms”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.
Extraction
Section titled “Extraction”getOrElse<B>(onNone: () => B): <A>(o: Option<A>) => A | BgetOrThrow<A>(option: Option<A>): AgetOrThrow(onNone: () => unknown): <A>(option: Option<A>) => Amatch<A, B, C>({ none: () => B, some: (a: A) => C }): (o: Option<A>) => B | CtoNullable<A>(o: Option<A>): A | nulltoUndefined<A>(o: Option<A>): A | undefinedtoResult<E>(onNone: () => E): <A>(o: Option<A>) => Result<A, E>Guards
Section titled “Guards”isSome<A>(o: Option<A>): o is Some<A>isNone<A>(o: Option<A>): o is NoneExamples
Section titled “Examples”import { pipe } from '@stopcock/fp'import * as O from '@stopcock/fp/option'
// safe env variable with validationconst 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 lookupspipe( O.fromNullable(user.address), O.flatMap((a) => O.fromNullable(a.zip)), O.match({ none: () => 'no zip', some: (zip) => zip, }),)
// convert to Result for error contextpipe( O.fromNullable(headers.authorization), O.toResult(() => 'missing auth header'),)