simple-monad
    Preparing search index...

    Class Result<A, B>

    An opt-in wrapper around an Ok / Bad leaf that adds chaining combinators (map, match, toUnion) and hosts the static unwrap* / matchBad toolkit. Build it with Result.from — the constructor is private.

    Type Parameters

    • A

      The success value type.

    • B extends Bad<ReasonType, unknown> = never

      The union of possible Bad failures (never if none).

    Index

    Chaining

    • Collapse to a single value by handling both arms. Each handler is required only when its rail is inhabited: an all-success Result<A, never> takes just { ok } (and rejects a dead bad), an all-failure Result<never, B> takes just { bad }.

      The bad arm is a per-reason map identical to Result.matchBad — one callback per failure tag, each receiving the Bad carrying that tag — so failures refine on their reason without a manual switch.

      Type Parameters

      • U

        The success handler's return type.

      • M extends unknown

        The bad per-reason handler map (see MatchBadInput).

      Parameters

      • handlers: MatchHandlers<A, B, U, M>

        ok receives the value; bad maps each reason tag to a handler for the matching Bad.

      Returns MatchResult<A, B, U, M>

      Whatever the chosen handler returns.

    Static toolkit

    • Dispatch on a failure's reason tag, like a switch over the Bad variants. The input must be a Bad (or a union of them): narrow away any Ok first, with a leaf guard or an earlier return. Passing a value that could still be an Ok is a compile error at the call site, rather than a | undefined that leaks into the result.

      Type Parameters

      • T extends Bad<string, unknown>

        The Bad (or Bad union) being matched.

      • M extends unknown

        The handler map (see MatchBadInput).

      Parameters

      • failure: T

        The failure to match — already narrowed to a Bad.

      • map: M

        One handler per reason tag; each receives the matching Bad.

      Returns MatchBadResult<T, M>

      The chosen handler's return value.

      ResultError if the failure's reason has no handler.

      const r = parse(input);
      if (r.isOk()) return r.value;
      // r is now a Bad union
      Result.matchBad(r, {
      nan: (b) => `not a number: ${b.value}`,
      });