Variable Result

Result: {
    Class: typeof Result;
    await<A, E>(m: Promise<A>): Promise<Result<A, E>>;
    fromJSON<A_3, E_3>(doc: {
        result: boolean;
        value: A_3 | E_3;
    }): Result<A_3, E_3>;
    is(value: unknown): value is Result<unknown, unknown>;
    lift<A_2, F, E_2>(fn: F): ((...args: Parameters<F>) => Result<A_2, E_2>);
    try<A_1, E_1>(f: (() => A_1)): Result<A_1, E_1>;
}

Static methods on the Result object.

Type declaration

  • Class: typeof Result

    The class constructor of Results. You should never use this to construct Results directly, preferring instead Ok and Err. It's exposed for use in instanceof checks, though calling Result.is to decide resultiness is preferred.

    import { expect } from "chai";
    expect(Ok("stop dots")).to.be.an.instanceof(Result.Class);
  • await:function
    • Convert a Promise returning A into a Promise returning a Result of either A or the Error type. The new Promise always succeeds, reflecting an error condition in the Result instead of the failure callback.

      Type Parameters

      Parameters

      Returns Promise<Result<A, E>>

      const fetchResult = await Result.await(fetch("https://example.com/example.txt"));
      if (fetchResult.isErr()) {
      console.error(fetchResult.value.message);
      }
  • fromJSON:function
  • is:function
    • Test whether an unknown value is a Result.

      Parameters

      • value: unknown

      Returns value is Result<unknown, unknown>

      function assertResult(value: unknown): void {
      if (Result.is(value)) {
      value.assertOk();
      }
      }
  • lift:function
    • Turn a function that returns A and potentially throws E into a function that catches E if thrown and returns Result<A, E>.

      Beware that TypeScript's type inference isn't currently very good at this, so you should explicitly provide the target function signature when using this function, or you're likely to end up with a Result<unknown, unknown> instead of the expected Result<A, E>.

      Type Parameters

      • A_2
      • F extends ((...args: any[]) => A_2)
      • E_2 = unknown

      Parameters

      • fn: F

      Returns ((...args: Parameters<F>) => Result<A_2, E_2>)

      function div(n: number, by: number): number {
      if (by === 0) {
      throw new RangeError("division by zero");
      }
      return n / by;
      }
      const liftedDiv: (n: number, by: number) => Result<number, RangeError> =
      Result.lift(div);
  • try:function
    • Run a function and return its result as an Ok if it didn't throw any exceptions, or an Err containing the thrown exception.

      Type Parameters

      • A_1
      • E_1 = unknown

      Parameters

      Returns Result<A_1, E_1>

      const tryFn: Result<number, Error> = Result.try(() => {
      throw new Error("fix the bug!");
      });

      if (tryFn.isErr()) {
      console.error(tryFn.value.message);
      }