UNPKG

monads-co

Version:

An implementation of Haskell's type classes in TS

90 lines (89 loc) 3.04 kB
import { Monad, MonadHKT } from './Monad'; export interface OptionalHKT extends MonadHKT { output: Optional<this["input"]>; } export declare class Optional<ValueT> extends Monad<ValueT> { _success: boolean; _value: ValueT | undefined | null; constructor(_success: boolean, _value: ValueT | undefined | null); /** * Used to wrap a function that can potentially return null or undefined in a safe wrapper * ```ts * const safeQuerySelector = Optional.wrap(document.querySelector) * ``` * @param fn */ static wrap<FnT extends (...args: any[]) => any>(fn: FnT): (...args: Parameters<FnT>) => Optional<NonNullable<ReturnType<FnT>>>; /** * If a value is held, this uses the mapping function to transform it, and returns Optional<New Value> * otherwise, it returns None() * @param mapping */ map<B>(mapping: (value: ValueT) => B): Optional<B>; amap<B>(mapping: Optional<(value: ValueT) => B>): Optional<B>; pure<B>(value: B): Optional<B>; /** * If a value is held the mapping is preformed on it, otherwise None() is returned. If you want to just transform * ValueT to a new Value, use `.map` * @param mapping */ then<B>(mapping: (value: ValueT) => Optional<B>): Optional<B>; /** * Returns the value is defined, otherwise it returns `defaultValue` * @param defaultValue */ or<B>(defaultValue: B): ValueT | B; /** * If None() replace it with a value * @param mapping */ catch<NewErrorT>(mapping: () => ValueT): Optional<ValueT>; /** * If None() replaces it with the result of the mapping * @param mapping */ catchThen<NewErrorT>(mapping: () => Optional<ValueT>): Optional<ValueT>; /** * Returns the value if Some(), otherwise it throws a reference error. * This is the nuclear option, `.or(default)` should be preferred. */ unwrap(): ValueT; } /** * Used to construct Some value, for example: * * @example * ```ts * // Gets all but the start of the string; IE "string" -> "tring" * function getStringTail(input: string): Optional<string> { * if (input.length <= 1) { * return None() * } else { * return Some(input.slice(1)) * } * } * ``` * @param value */ export declare function Some<ValueT>(value: ValueT): Optional<ValueT>; /** * Used to construct Some value, for example: * * @example * ```ts * // Gets all but the start of the string; IE "string" -> "tring" * function getStringTail(input: string): Optional<string> { * if (input.length <= 1) { * return None() * } else { * return Some(input.slice(1)) * } * } * ``` */ export declare function None<ValueT>(): Optional<ValueT>; /** * Like Some() or None() but it doesn't mind if you give it a value or not. * @param value */ export declare function Maybe<ValueT>(value?: ValueT | undefined | null): Optional<NonNullable<ValueT>>;