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>(pred: (a: A) => boolean): (a: A) => Option<A>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: (a: A) => boolean): (o: Option<A>) => Option<A>tap<A>(f: (a: A) => void): (o: Option<A>) => Option<A>Extraction
Section titled “Extraction”getOrElse<B>(onNone: () => B): <A>(o: Option<A>) => A | BgetWithDefault<B>(value: B): <A>(o: Option<A>) => A | Bmatch<B, A, C = B>(onNone: () => B, onSome: (a: A) => C): (o: Option<A>) => B | CtoNullable<A>(o: Option<A>): A | nulltoUndefined<A>(o: Option<A>): A | undefinedtoResult<E>(defaultError: 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, O } from '@stopcock/fp'
// 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),)
// chain nullable lookupspipe( O.fromNullable(user.address), O.flatMap(a => O.fromNullable(a.zip)), O.match(() => 'no zip', zip => zip),)
// convert to Result for error contextpipe( O.fromNullable(headers.authorization), O.toResult('missing auth header'),)