ts-fortress
    Preparing search index...

    Function match

    • Folds a Result into a plain value by applying one of two case handlers: ok if the Result is Ok, err otherwise. This is the function form of pattern matching on a Result.

      Unlike Result.fold, which maps both sides and returns another Result, match unwraps: both branches produce the final value directly.

      Type Parameters

      • R extends UnknownResult

        The input UnknownResult type.

      • S2

        The type returned by the ok case.

      • E2

        The type returned by the err case.

      Parameters

      • result: R

        The Result to match on.

      • cases: Readonly<{ err: (error: UnwrapErr<R>) => E2; ok: (value: UnwrapOk<R>) => S2 }>

        An object with an ok handler receiving the success value and an err handler receiving the error value.

      Returns S2 | E2

      The value produced by whichever case handler was applied.

      const doubledOrZero = Result.match(Result.ok(21), {
      ok: (value) => value * 2,
      err: () => 0,
      });

      assert.deepStrictEqual(doubledOrZero, 42);

      const matcher = Result.match({
      ok: (value: number) => value + 1,
      err: (error: string) => error.length,
      });

      assert.deepStrictEqual(matcher(Result.ok(1)), 2);

      assert.deepStrictEqual(matcher(Result.err('oops')), 4);
    • Folds a Result into a plain value by applying one of two case handlers: ok if the Result is Ok, err otherwise. This is the function form of pattern matching on a Result.

      Unlike Result.fold, which maps both sides and returns another Result, match unwraps: both branches produce the final value directly.

      Type Parameters

      • S
      • E
      • S2

        The type returned by the ok case.

      • E2

        The type returned by the err case.

      Parameters

      • cases: Readonly<{ err: (error: E) => E2; ok: (value: S) => S2 }>

        An object with an ok handler receiving the success value and an err handler receiving the error value.

      Returns <R extends UnknownResult>(
          result: UnwrapOk<R> extends S
              ? UnwrapErr<R> extends E ? R : never
              : never,
      ) => S2 | E2

      The value produced by whichever case handler was applied.

      const doubledOrZero = Result.match(Result.ok(21), {
      ok: (value) => value * 2,
      err: () => 0,
      });

      assert.deepStrictEqual(doubledOrZero, 42);

      const matcher = Result.match({
      ok: (value: number) => value + 1,
      err: (error: string) => error.length,
      });

      assert.deepStrictEqual(matcher(Result.ok(1)), 2);

      assert.deepStrictEqual(matcher(Result.err('oops')), 4);