typesafe-ts API Documentation - v1.2.0
    Preparing search index...

    Interface Result<ResultType, ErrorType>

    interface Result<ResultType, ErrorType extends Error> {
        get "[toStringTag]"(): "Result";
        is_error(): this is ErrorResult<ErrorType>;
        is_ok(): this is OkResult<ResultType>;
        value_or(value_if_error: ResultType): ResultType;
        error_or(error_if_ok: ErrorType): ErrorType;
        map<NewResultType>(
            fn: (value: ResultType) => NewResultType,
        ): Result<NewResultType, ErrorType>;
        map_err<NewErrorType extends Error>(
            fn: (error: ErrorType) => NewErrorType,
        ): Result<ResultType, NewErrorType>;
        match<OKMatchResultType, ErrorMatchResultType>(
            handlers: {
                on_ok: (value: ResultType) => OKMatchResultType;
                on_error: (error: ErrorType) => ErrorMatchResultType;
            },
        ): OKMatchResultType
        | ErrorMatchResultType;
        and_then<NewResultType>(
            fn: (value: ResultType) => Result<NewResultType, ErrorType>,
        ): Result<NewResultType, ErrorType>;
        or_else<NewErrorType extends Error>(
            fn: (error: ErrorType) => Result<ResultType, NewErrorType>,
        ): Result<ResultType, NewErrorType>;
        "[iterator]"(): Generator<ResultType, void, unknown>;
    }

    Type Parameters

    • ResultType
    • ErrorType extends Error
    Index

    Accessors

    • get "[toStringTag]"(): "Result"

      Returns the string tag for Object.prototype.toString calls. Always returns "Result" for Result instances.

      Returns "Result"

    Methods

    • Type predicate that checks if this Result contains an error. If true, TypeScript will narrow the type to include the error property.

      Returns this is ErrorResult<ErrorType>

      True if this Result contains an error, false if it contains a value

      const result = result.error(new Error("Something went wrong"));
      if (result.is_error()) {
      console.log(result.error.message); // TypeScript knows .error exists
      }
    • Type predicate that checks if this Result contains a success value. If true, TypeScript will narrow the type to include the value property.

      Returns this is OkResult<ResultType>

      True if this Result contains a value, false if it contains an error

      const result = result.ok("Hello, World!");
      if (result.is_ok()) {
      console.log(result.value); // TypeScript knows .value exists
      }
    • Returns the contained value if Ok, otherwise returns the provided default value.

      Parameters

      • value_if_error: ResultType

        The value to return if this Result contains an error

      Returns ResultType

      The contained value if Ok, otherwise the default value

      const success = result.ok(42);
      console.log(success.value_or(0)); // 42

      const failure = result.error(new Error("Failed"));
      console.log(failure.value_or(0)); // 0
    • Returns the contained error if Error, otherwise returns the provided default error.

      Parameters

      • error_if_ok: ErrorType

        The error to return if this Result contains a value

      Returns ErrorType

      The contained error if Error, otherwise the default error

      const failure = result.error(new Error("Original error"));
      console.log(failure.error_or(new Error("Default"))); // Error: Original error

      const success = result.ok("value");
      console.log(success.error_or(new Error("Default"))); // Error: Default
    • Transforms the contained value if Ok, otherwise returns the error unchanged. This is the functor map operation for Result.

      Type Parameters

      • NewResultType

        The type of the transformed value

      Parameters

      Returns Result<NewResultType, ErrorType>

      A new Result with the transformed value if Ok, otherwise the original error

      const success = result.ok(5);
      const doubled = success.map(x => x * 2);
      console.log(doubled.value_or(0)); // 10

      const failure = result.error(new Error("Failed"));
      const transformed = failure.map(x => x * 2); // fn is not called
      console.log(transformed.is_error()); // true
    • Transforms the contained error if Error, otherwise returns the value unchanged. This allows for error transformation and chaining.

      Type Parameters

      • NewErrorType extends Error

        The type of the transformed error

      Parameters

      Returns Result<ResultType, NewErrorType>

      A new Result with the transformed error if Error, otherwise the original value

      const failure = result.error(new Error("Original"));
      const wrapped = failure.map_err(err => new Error(`Wrapped: ${err.message}`));
      if (wrapped.is_error()) {
      console.log(wrapped.error.message); // "Wrapped: Original"
      }

      const success = result.ok("value");
      const unchanged = success.map_err(err => new Error("Won't be called"));
      console.log(unchanged.is_ok()); // true
    • Pattern matches against the Result, executing the appropriate callback and returning its result. This is useful when you need to transform both Ok and Error cases into the same output type.

      Type Parameters

      • OKMatchResultType

        The return type of the on_ok callback

      • ErrorMatchResultType

        The return type of the on_error callback

      Parameters

      Returns OKMatchResultType | ErrorMatchResultType

      The result of the executed callback

      const success = result.ok(42);
      const message = success.match({
      on_ok: (value) => `Value is ${value}`,
      on_error: (error) => `Error occurred: ${error.message}`,
      });
      console.log(message); // "Value is 42"

      const failure = result.error(new Error("Something went wrong"));
      const errorMessage = failure.match({
      on_ok: (value) => `Value is ${value}`,
      on_error: (error) => `Error occurred: ${error.message}`,
      });
      console.log(errorMessage); // "Error occurred: Something went wrong"
    • Monadic bind operation. Chains another Result-returning operation if this Result is Ok. If this Result is Error, the function is not called and the error is propagated. This is also known as flatMap in some languages.

      Type Parameters

      • NewResultType

        The type of the value in the returned Result

      Parameters

      Returns Result<NewResultType, ErrorType>

      The Result returned by fn if Ok, otherwise the original error

      function parseNumber(str: string): Result<number, Error> {
      const num = Number(str);
      return isNaN(num) ? result.error(new Error("Not a number")) : result.ok(num);
      }

      function divide(a: number, b: number): Result<number, Error> {
      return b === 0 ? result.error(new Error("Division by zero")) : result.ok(a / b);
      }

      const computation = parseNumber("10")
      .and_then(num => divide(num, 2));

      if (computation.is_ok()) {
      console.log(computation.value); // 5
      }
    • Provides a fallback Result if this Result is Error. If this Result is Ok, the function is not called and the value is preserved. This allows for error recovery and alternative computation paths.

      Type Parameters

      • NewErrorType extends Error

        The type of error in the fallback Result

      Parameters

      Returns Result<ResultType, NewErrorType>

      The fallback Result returned by fn if Error, otherwise the original Ok value

      function tryPrimary(): Result<string, Error> {
      return result.error(new Error("Primary failed"));
      }

      function tryFallback(): Result<string, Error> {
      return result.ok("Fallback success");
      }

      const outcome = tryPrimary()
      .or_else(() => tryFallback());

      if (outcome.is_ok()) {
      console.log(outcome.value); // "Fallback success"
      }
    • Returns a generator that yields the contained value if this Result is Ok. If this Result is Error, the generator yields nothing (completes immediately). This allows for easy iteration over successful values in for-of loops and other iterator contexts.

      Returns Generator<ResultType, void, unknown>

      A generator that yields the value if Ok, otherwise yields nothing

      const success = result.ok(42);
      for (const value of success) {
      console.log(value); // 42
      }

      const failure = result.error(new Error("Failed"));
      for (const value of failure) {
      console.log("This won't execute");
      }

      // Useful for collecting successful values from multiple results
      const results = [
      result.ok(1),
      result.error(new Error("Failed")),
      result.ok(3)
      ];

      const values = [];
      for (const res of results) {
      for (const value of res) {
      values.push(value);
      }
      }
      console.log(values); // [1, 3]