TS-Scribe - v0.6.2
    Preparing search index...

    Function maybe

    • Create a Maybe monad from a value, a factory function, or an existing Maybe.

      • If init is already a Maybe, it is returned as-is.
      • If init is a function, it is called and its return value is wrapped.
      • If the resolved value is null or undefined, an empty monad is returned (equivalent to maybe.empty).
      • Errors thrown by a factory are caught and produce an error monad (equivalent to maybe.error).

      Type Parameters

      • TypedValue

      Parameters

      • init:
            | TypedValue
            | Maybe<TypedValue>
            | (() => Nullish | TypedValue | Maybe<TypedValue>)
            | undefined

        A value, a zero-argument factory, or an existing Maybe.

      Returns Maybe<TypedValue>

      A Maybe monad wrapping the resolved value.

      // Wrap a plain value
      maybe(42).value; // 42

      // Wrap a factory – nullish return becomes empty
      maybe(() => null).empty; // true

      // Pass-through an existing Maybe
      const m = maybe(42);
      maybe(m) === m; // true

      // Errors thrown in a factory become error monads
      maybe(() => { throw new Error('!'); }).error; // Error: !

      // Nullish init becomes empty
      maybe(undefined).empty; // true
    Index

    Methods

    Methods

    • Return the shared empty monad singleton — an empty monad with no associated error.

      Because there is no error, catch is a no-op on this monad; use else to provide a fallback instead. All calls return the same instance.

      Type Parameters

      • TypedValue = never

      Returns Maybe<TypedValue>

      The shared empty Maybe singleton.

      const m = maybe.empty<number>();
      m.ok; // false
      m.empty; // true
      m.error; // null

      // Provide a fallback with else
      m.else(0).value; // 0

      // catch is a no-op – use else instead
      m.catch(() => 0).ok; // false

      // All instances are identical
      maybe.empty() === maybe.empty(); // true
    • Create an empty monad carrying an error.

      If error is omitted or nullish, a generic Error('unknown') is used so the monad always has a non-nullish error property. Use this variant (rather than maybe.empty) when you want downstream catch handlers to run.

      Type Parameters

      • TypedValue = never

      Parameters

      • Optionalerror: unknown

        The error value to associate with the monad. Defaults to new Error('unknown') when omitted.

      Returns Maybe<TypedValue>

      An empty Maybe carrying the given error.

      const m = maybe.error(new TypeError('bad input'));
      m.ok; // false
      m.empty; // true
      m.error; // TypeError: bad input

      // Recover with catch
      m.catch((err) => `Handled: ${err.message}`).value;
      // 'Handled: bad input'

      // catch is a no-op on maybe.empty() (error is null)
      maybe.empty().catch(() => 'x').ok; // false