happy-rusty
    Preparing search index...

    Interface Result<T, E>

    The Result type is used for returning and propagating errors. It is an enum with the variants, Ok(T), representing success and containing a value, and Err(E), representing error and containing an error value. This interface includes methods that act on the Result type, similar to Rust's Result enum.

    As Rust Code:

    pub enum Result<T, E> {
    Ok(T),
    Err(E),
    }
    interface Result<T, E> {
        "[ResultKindSymbol]": "Ok" | "Err";
        "[toStringTag]": "Result";
        "[iterator]"(): Iterator<T>;
        and<U>(other: Result<U, E>): Result<U, E>;
        andThen<U>(fn: (value: T) => Result<U, E>): Result<U, E>;
        andThenAsync<U>(
            fn: (value: T) => AsyncLikeResult<U, E> | Result<U, E>,
        ): AsyncResult<U, E>;
        andTryAsync<U>(
            fn: (value: T) => U | PromiseLike<U>,
        ): AsyncResult<Awaited<U>, E>;
        asErr<U>(): Result<U, E>;
        asOk<F>(): Result<T, F>;
        eq(other: Result<T, E>): boolean;
        err(): Option<E>;
        expect(msg: string): T;
        expectErr(msg: string): E;
        flatten<U>(this: Result<Result<U, E>, E>): Result<U, E>;
        inspect(fn: (value: T) => void): this;
        inspectErr(fn: (error: E) => void): this;
        intoErr(this: Result<never, E>): E;
        intoOk(this: Result<T, never>): T;
        isErr(): boolean;
        isErrAnd(predicate: (error: E) => boolean): boolean;
        isErrAndAsync(
            predicate: (error: E) => boolean | PromiseLike<boolean>,
        ): Promise<boolean>;
        isOk(): boolean;
        isOkAnd(predicate: (value: T) => boolean): boolean;
        isOkAndAsync(
            predicate: (value: T) => boolean | PromiseLike<boolean>,
        ): Promise<boolean>;
        map<U>(fn: (value: T) => U): Result<U, E>;
        mapErr<F>(fn: (error: E) => F): Result<T, F>;
        mapOr<U>(defaultValue: U, fn: (value: T) => U): U;
        mapOrElse<U>(defaultFn: (error: E) => U, fn: (value: T) => U): U;
        ok(): Option<T>;
        or<F>(other: Result<T, F>): Result<T, F>;
        orElse<F>(fn: (error: E) => Result<T, F>): Result<T, F>;
        orElseAsync<F>(
            fn: (error: E) => AsyncLikeResult<T, F> | Result<T, F>,
        ): AsyncResult<T, F>;
        orTryAsync<F>(
            fn: (error: E) => T | PromiseLike<T>,
        ): AsyncResult<Awaited<T>, F>;
        toString(): string;
        transpose<U>(this: Result<Option<U>, E>): Option<Result<U, E>>;
        unwrap(): T;
        unwrapErr(): E;
        unwrapOr(defaultValue: T): T;
        unwrapOrElse(fn: (error: E) => T): T;
        unwrapOrElseAsync(
            fn: (error: E) => T | PromiseLike<T>,
        ): Promise<Awaited<T>>;
    }

    Type Parameters

    • T

      The type of the value contained in a successful Result.

    • E

      The type of the error contained in an unsuccessful Result.

    Index

    Properties

    "[ResultKindSymbol]": "Ok" | "Err"

    A unique symbol property used to identify the variant of this Result. Returns 'Ok' if the Result represents success, or 'Err' if it represents failure.

    This is used internally by the isResult utility function to verify that an object is a valid Result instance, and to distinguish between Ok and Err variants without calling methods.

    Note: The symbol itself is not exported as part of the public API. Use the isResult utility function or the isOk()/isErr() methods for type checking.

    "[toStringTag]": "Result"

    The well-known symbol Symbol.toStringTag used by Object.prototype.toString(). Returns 'Result' so that Object.prototype.toString.call(result) produces '[object Result]'.

    This enables reliable type identification even across different execution contexts (e.g., iframes, different module instances).

    const x = Ok(5);
    console.log(Object.prototype.toString.call(x)); // '[object Result]'

    Methods

    • Implements the Iterator protocol, allowing Result to be used with for...of loops and spread syntax.

      • For Ok(value), yields the contained value once.
      • For Err(error), yields nothing (empty iterator).

      This is similar to Rust's Result::iter() method.

      Returns Iterator<T>

      An iterator that yields zero or one value.

      // Using with for...of
      for (const value of Ok(5)) {
      console.log(value); // 5
      }

      for (const value of Err('error')) {
      console.log(value); // never executed
      }

      // Using with spread operator
      const arr1 = [...Ok(5)]; // [5]
      const arr2 = [...Err('error')]; // []

      // Using with Array.from
      Array.from(Ok('hello')); // ['hello']
      Array.from(Err('error')); // []
    • Returns this if the result is Err, otherwise returns the passed Result.

      Type Parameters

      • U

        The type of the value in the other Result.

      Parameters

      • other: Result<U, E>

        The Result to return if this is Ok.

      Returns Result<U, E>

      The passed Result if this is Ok, otherwise returns this (which is Err).

      or

      const x = Ok(2);
      const y = Err('late error');
      console.log(x.and(y).unwrapErr()); // 'late error'

      const a = Err('early error');
      const b = Ok(5);
      console.log(a.and(b).unwrapErr()); // 'early error'
    • Calls the provided function with the contained value if this is Ok, otherwise returns this as Err.

      Type Parameters

      • U

        The type of the value returned by the function.

      Parameters

      • fn: (value: T) => Result<U, E>

        A function that takes the Ok value and returns a Result.

      Returns Result<U, E>

      The result of fn if this is Ok, otherwise this as Err.

      • map
      • orElse
      const x = Ok(2);
      const result = x.andThen(v => v > 0 ? Ok(v * 2) : Err('negative'));
      console.log(result.unwrap()); // 4

      const y = Err('error');
      console.log(y.andThen(v => Ok(v * 2)).unwrapErr()); // 'error'
    • Asynchronous version of andThen.

      Type Parameters

      • U

        The type of the value returned by the function.

      Parameters

      • fn: (value: T) => AsyncLikeResult<U, E> | Result<U, E>

        A function that takes the Ok value and returns PromiseLike<Result<U, E>> or Result<U, E>.

      Returns AsyncResult<U, E>

      A promise that resolves to this as Err if this is Err, otherwise the result of fn.

      • andThen
      • orElseAsync
      const x = Ok(2);
      const result = await x.andThenAsync(async v => Ok(v * 2));
      console.log(result.unwrap()); // 4
    • Non-standard extension: This method is not part of Rust's standard library.

      Like andThenAsync, but automatically catches any thrown exceptions or Promise rejections and converts them to Err.

      This is useful when calling async functions that may throw, without needing to wrap the call in tryAsyncResult.

      Note: The error type E is preserved. If the function throws, the thrown value is cast to E. The caller is responsible for ensuring that thrown exceptions are compatible with type E, similar to how tryAsyncResult<T, E> works.

      Type Parameters

      • U

        The type of the value returned by the function.

      Parameters

      • fn: (value: T) => U | PromiseLike<U>

        A function that takes the Ok value and returns PromiseLike<U> or U. May throw or reject.

      Returns AsyncResult<Awaited<U>, E>

      A promise that resolves to Ok(U) if successful, or Err(E) if this is Err or if fn throws/rejects.

      1.9.0

      • andThenAsync
      • tryAsyncResult
      const x: Result<number, Error> = Ok(2);

      // If the async function succeeds
      const result = await x.andTryAsync(async v => {
      const response = await fetch(`/api/multiply/${v}`);
      return response.json();
      });
      console.log(result.unwrap()); // { value: 4 }

      // If the async function throws or rejects
      const failed = await x.andTryAsync(async v => {
      throw new Error('Network error');
      });
      console.log(failed.unwrapErr()); // Error: Network error

      // If this is already Err, fn is not called
      const y: Result<number, Error> = Err(new Error('original error'));
      const skipped = await y.andTryAsync(async v => v * 2);
      console.log(skipped.unwrapErr()); // Error: original error
    • Transforms the current Result into a new Result where the type of the success value is replaced with a new type U. The type of the error remains unchanged. This is a type-level only operation, equivalent to result as unknown as Result<U, E>. Useful when you need to propagate an error to a different success type context.

      Type Parameters

      • U

        The new type for the success value.

      Returns Result<U, E>

      this with the success type cast to U.

      asOk

      const x: Result<number, string> = Err('error');
      const y: Result<string, string> = x.asErr<string>();
      console.log(y.unwrapErr()); // 'error'
    • Transforms the current Result into a new Result where the type of the error is replaced with a new type F. The type of the success value remains unchanged. This is a type-level only operation, equivalent to result as unknown as Result<T, F>.

      Type Parameters

      • F

        The new type for the error.

      Returns Result<T, F>

      this with the error type cast to F.

      asErr

      const x: Result<number, string> = Ok(5);
      const y: Result<number, Error> = x.asOk<Error>();
      console.log(y.unwrap()); // 5
    • Tests whether this and other are both Ok containing equal values, or both are Err containing equal errors.

      Parameters

      • other: Result<T, E>

        The other Result to compare with.

      Returns boolean

      true if this and other are both Ok with equal values, or both are Err with equal errors, otherwise false.

      const a = Ok(5);
      const b = Ok(5);
      const c = Ok(10);
      console.log(a.eq(b)); // true
      console.log(a.eq(c)); // false

      const d = Err('error');
      const e = Err('error');
      console.log(d.eq(e)); // true
      console.log(a.eq(d)); // false
    • Converts from Result<T, E> to Option<E>. If the result is Err, returns Some(E). If the result is Ok, returns None.

      Returns Option<E>

      ok

      const x = Err('error');
      console.log(x.err().unwrap()); // 'error'

      const y = Ok(5);
      console.log(y.err().isNone()); // true
    • Returns the contained Ok value, with a provided error message if the result is Err.

      Parameters

      • msg: string

        The error message to provide if the result is an Err.

      Returns T

      Throws an error with the provided message if the result is an Err.

      • unwrap
      • expectErr
      • intoOk
      const x = Ok(5);
      console.log(x.expect('should have value')); // 5

      const y = Err('error');
      y.expect('should have value'); // throws TypeError: should have value: error
    • Returns the contained Err value, with a provided error message if the result is Ok.

      Parameters

      • msg: string

        The error message to provide if the result is an Ok.

      Returns E

      Throws an error with the provided message if the result is an Ok.

      • unwrapErr
      • expect
      • intoErr
      const x = Err('error');
      console.log(x.expectErr('should have error')); // 'error'

      const y = Ok(5);
      y.expectErr('should have error'); // throws TypeError: should have error: 5
    • Converts from Result<Result<U, E>, E> to Result<U, E>. If the result is Ok(Ok(U)), returns Ok(U). If the result is Ok(Err(E)) or Err(E), returns Err(E).

      Type Parameters

      • U

        The type of the success value in the inner Result.

      Parameters

      Returns Result<U, E>

      const x = Ok(Ok(5));
      console.log(x.flatten().unwrap()); // 5

      const y = Ok(Err('error'));
      console.log(y.flatten().unwrapErr()); // 'error'
    • Calls the provided function with the contained value if this is Ok, for side effects only. Does not modify the Result.

      Parameters

      • fn: (value: T) => void

        A function to call with the Ok value.

      Returns this

      this, unmodified.

      inspectErr

      const x = Ok(5);
      x.inspect(v => console.log(v)); // prints 5
    • Calls the provided function with the contained error if this is Err, for side effects only. Does not modify the Result.

      Parameters

      • fn: (error: E) => void

        A function to call with the Err value.

      Returns this

      this, unmodified.

      inspect

      const x = Err('error');
      x.inspectErr(e => console.log(e)); // prints 'error'
    • Returns the contained Err value.

      Unlike unwrapErr, this method is known to never throw because the success type is never, meaning the Ok variant can never occur.

      This provides a compile-time guarantee that the extraction is safe. If someone later changes the ok type to one that can occur, the code will fail to compile rather than potentially throwing at runtime.

      Parameters

      Returns E

      The contained Err value.

      • unwrapErr
      • expectErr
      • intoOk
      function alwaysFails(): Result<never, string> {
      return Err('error');
      }

      // Safe extraction - compiler knows this can never be Ok
      const error: string = alwaysFails().intoErr();
    • Returns the contained Ok value.

      Unlike unwrap, this method is known to never throw because the error type is never, meaning the Err variant can never occur.

      This provides a compile-time guarantee that the extraction is safe. If someone later changes the error type to one that can occur, the code will fail to compile rather than potentially throwing at runtime.

      Parameters

      Returns T

      The contained Ok value.

      • unwrap
      • expect
      • intoErr
      function alwaysSucceeds(): Result<string, never> {
      return Ok('success');
      }

      // Safe extraction - compiler knows this can never be Err
      const value: string = alwaysSucceeds().intoOk();
    • Returns true if the result is Err.

      Returns boolean

      const x = Ok(5);
      console.log(x.isErr()); // false

      const y = Err('error');
      console.log(y.isErr()); // true
    • Returns true if the result is Err and the provided predicate returns true for the contained error.

      Parameters

      • predicate: (error: E) => boolean

        A function that takes the Err value and returns a boolean.

      Returns boolean

      isOkAnd

      const x = Err('error');
      console.log(x.isErrAnd(e => e === 'error')); // true
    • Asynchronous version of isErrAnd.

      Parameters

      • predicate: (error: E) => boolean | PromiseLike<boolean>

        A function that takes the Err value and returns a PromiseLike<boolean> or boolean.

      Returns Promise<boolean>

      A promise that resolves to true if the Result is Err and the predicate resolves to true.

      • isErrAnd
      • isOkAndAsync
      const x = Err('error');
      await x.isErrAndAsync(async e => e.length > 0); // true
    • Returns true if the result is Ok.

      Returns boolean

      const x = Ok(5);
      console.log(x.isOk()); // true

      const y = Err('error');
      console.log(y.isOk()); // false
    • Returns true if the result is Ok and the provided predicate returns true for the contained value.

      Parameters

      • predicate: (value: T) => boolean

        A function that takes the Ok value and returns a boolean.

      Returns boolean

      isErrAnd

      const x = Ok(2);
      console.log(x.isOkAnd(v => v > 1)); // true
      console.log(x.isOkAnd(v => v > 5)); // false
    • Asynchronous version of isOkAnd.

      Parameters

      • predicate: (value: T) => boolean | PromiseLike<boolean>

        A function that takes the Ok value and returns a PromiseLike<boolean> or boolean.

      Returns Promise<boolean>

      A promise that resolves to true if the Result is Ok and the predicate resolves to true.

      • isOkAnd
      • isErrAndAsync
      const x = Ok(2);
      await x.isOkAndAsync(async v => v > 1); // true
    • Maps a Result<T, E> to Result<U, E> by applying a function to a contained Ok value, leaving an Err value untouched.

      Type Parameters

      • U

        The type of the value returned by the map function.

      Parameters

      • fn: (value: T) => U

        A function that takes the Ok value and returns a new value.

      Returns Result<U, E>

      • mapErr
      • andThen
      const x = Ok(5);
      console.log(x.map(v => v * 2).unwrap()); // 10

      const y = Err('error');
      console.log(y.map(v => v * 2).unwrapErr()); // 'error'
    • Maps a Result<T, E> to Result<T, F> by applying a function to a contained Err value, leaving an Ok value untouched.

      Type Parameters

      • F

        The type of the error returned by the map function.

      Parameters

      • fn: (error: E) => F

        A function that takes the Err value and returns a new error value.

      Returns Result<T, F>

      map

      const x = Err('error');
      console.log(x.mapErr(e => e.toUpperCase()).unwrapErr()); // 'ERROR'
    • Maps a Result<T, E> to U by applying a function to the contained Ok value (if Ok), or returns the provided default (if Err).

      Type Parameters

      • U

        The type of the value returned by the map function or the default value.

      Parameters

      • defaultValue: U

        The value to return if the result is Err.

      • fn: (value: T) => U

        A function that takes the Ok value and returns a new value.

      Returns U

      mapOrElse

      const x = Ok(5);
      console.log(x.mapOr(0, v => v * 2)); // 10

      const y = Err('error');
      console.log(y.mapOr(0, v => v * 2)); // 0
    • Maps a Result<T, E> to U by applying a function to the contained Ok value (if Ok), or computes a default (if Err).

      Type Parameters

      • U

        The type of the value returned by the map function or the default function.

      Parameters

      • defaultFn: (error: E) => U

        A function that returns the default value.

      • fn: (value: T) => U

        A function that takes the Ok value and returns a new value.

      Returns U

      mapOr

      const x = Ok(5);
      console.log(x.mapOrElse(e => 0, v => v * 2)); // 10

      const y = Err('error');
      console.log(y.mapOrElse(e => e.length, v => v * 2)); // 5
    • Converts from Result<T, E> to Option<T>. If the result is Ok, returns Some(T). If the result is Err, returns None.

      Returns Option<T>

      err

      const x = Ok(5);
      console.log(x.ok().unwrap()); // 5

      const y = Err('error');
      console.log(y.ok().isNone()); // true
    • Returns this if it is Ok, otherwise returns the passed Result.

      Type Parameters

      • F

        The type of the error in the other Result.

      Parameters

      • other: Result<T, F>

        The Result to return if this is Err.

      Returns Result<T, F>

      this if it is Ok, otherwise returns other.

      and

      const x = Err('error');
      const y = Ok(5);
      console.log(x.or(y).unwrap()); // 5

      const a = Ok(2);
      const b = Ok(100);
      console.log(a.or(b).unwrap()); // 2
    • Calls the provided function with the contained error if this is Err, otherwise returns this as Ok.

      Type Parameters

      • F

        The type of the error returned by the function.

      Parameters

      • fn: (error: E) => Result<T, F>

        A function that takes the Err value and returns a Result.

      Returns Result<T, F>

      The result of fn if this is Err, otherwise this as Ok.

      andThen

      const x = Err('error');
      const result = x.orElse(e => Ok(e.length));
      console.log(result.unwrap()); // 5

      const y = Ok(2);
      console.log(y.orElse(e => Ok(0)).unwrap()); // 2
    • Asynchronous version of orElse.

      Type Parameters

      • F

        The type of the error returned by the function.

      Parameters

      • fn: (error: E) => AsyncLikeResult<T, F> | Result<T, F>

        A function that takes the Err value and returns PromiseLike<Result<T, F>> or Result<T, F>.

      Returns AsyncResult<T, F>

      A promise that resolves to this as Ok if this is Ok, otherwise the result of fn.

      • orElse
      • andThenAsync
      const x = Err('error');
      const result = await x.orElseAsync(async e => Ok(e.length));
      console.log(result.unwrap()); // 5
    • Non-standard extension: This method is not part of Rust's standard library.

      Like orElseAsync, but automatically catches any thrown exceptions or Promise rejections and converts them to Err.

      This is useful when error recovery logic may itself throw, without needing to wrap the call in tryAsyncResult.

      Note: The error type F is preserved. If the function throws, the thrown value is cast to F. The caller is responsible for ensuring that thrown exceptions are compatible with type F, similar to how tryAsyncResult<T, E> works.

      Type Parameters

      • F

        The type of the error returned by the function.

      Parameters

      • fn: (error: E) => T | PromiseLike<T>

        A function that takes the Err value and returns PromiseLike<T> or T. May throw or reject.

      Returns AsyncResult<Awaited<T>, F>

      A promise that resolves to Ok(T) if this is Ok or if fn succeeds, or Err(F) if fn throws/rejects.

      1.9.0

      • orElseAsync
      • tryAsyncResult
      const x: Result<number, Error> = Err(new Error('primary failed'));

      // If the recovery function succeeds
      const result = await x.orTryAsync(async e => {
      const response = await fetch('/api/fallback');
      return response.json();
      });
      console.log(result.unwrap()); // { value: 42 }

      // If the recovery function throws or rejects
      const failed = await x.orTryAsync(async e => {
      throw new Error('fallback also failed');
      });
      console.log(failed.unwrapErr()); // Error: fallback also failed

      // If this is already Ok, fn is not called
      const y: Result<number, Error> = Ok(10);
      const skipped = await y.orTryAsync(async e => 999);
      console.log(skipped.unwrap()); // 10
    • Custom toString implementation that uses the Result's contained value.

      Returns string

      console.log(Ok(5).toString()); // 'Ok(5)'
      console.log(Err('error').toString()); // 'Err(error)'
    • Transposes a Result of an Option into an Option of a Result.

      Type Parameters

      • U

        The type of the success value in the Ok variant of the Option.

      Parameters

      Returns Option<Result<U, E>>

      Some containing Ok if the result is Ok containing Some, Some containing Err if the result is Err, None if the result is Ok containing None.

      const x = Ok(Some(5));
      console.log(x.transpose().unwrap().unwrap()); // 5

      const y: Result<Option<number>, string> = Err('error');
      console.log(y.transpose().unwrap().unwrapErr()); // 'error'

      const z = Ok(None);
      console.log(z.transpose().isNone()); // true
    • Returns the contained Ok value.

      Returns T

      Throws an error if the result is an Err.

      • expect
      • unwrapOr
      • unwrapErr
      • intoOk
      const x = Ok(5);
      console.log(x.unwrap()); // 5

      const y = Err('error');
      y.unwrap(); // throws TypeError
    • Returns the contained Err value.

      Returns E

      Throws an error if the result is an Ok.

      • expectErr
      • unwrap
      • intoErr
      const x = Err('error');
      console.log(x.unwrapErr()); // 'error'

      const y = Ok(5);
      y.unwrapErr(); // throws TypeError
    • Returns the contained Ok value or a provided default.

      Parameters

      • defaultValue: T

        The value to return if the result is an Err.

      Returns T

      unwrapOrElse

      const x = Ok(5);
      console.log(x.unwrapOr(10)); // 5

      const y = Err('error');
      console.log(y.unwrapOr(10)); // 10
    • Returns the contained Ok value or computes it from a closure if the result is Err.

      Parameters

      • fn: (error: E) => T

        A function that takes the Err value and returns an Ok value.

      Returns T

      unwrapOr

      const x = Err('error');
      console.log(x.unwrapOrElse(e => e.length)); // 5
    • Asynchronous version of unwrapOrElse.

      Parameters

      • fn: (error: E) => T | PromiseLike<T>

        A function that takes the Err value and returns PromiseLike<T> or T.

      Returns Promise<Awaited<T>>

      A promise that resolves to the contained Ok value or the result of the function.

      unwrapOrElse

      const x = Err('error');
      await x.unwrapOrElseAsync(async e => e.length); // 5