Options
All
  • Public
  • Public/Protected
  • All
Menu

Error handling with the Result type.

Result<T, E> is the type used for returning and propagating errors. Ok(T), representing success and containing a value, and Err(E), representing error and containing an error value.

Type parameters

  • T

  • E

Hierarchy

  • Result

Implements

Index

Methods

andThen

  • andThen<U, F>(fn: F): Result<U, E>
  • Calls op if the result is Ok, otherwise returns the Err value of self.

    This function can be used for control flow based on Result values.

    Example

    const ok = Ok(25);
    const sq = (x: number) => Ok(x * x);
    
    // 25 * 25 => 625 + 5 => 630
    const result = ok.andThen(sq).andThen((x) => Ok(x + 5));
    expect(result.unwrap()).toEqual(630);
    

    Type parameters

    • U

    • F: (data: T) => Result<U, E>

    Parameters

    • fn: F

    Returns Result<U, E>

clone

  • Returns Result<T, E>

err

  • Converts from Result<T, E> to Option<E>. Converts self into an Option<E>, consuming self, and discarding the success value, if any.

    Example

    const ok = Ok("ok");
    expect(ok.err()).toEqual(None());
    
    const err = Err("err");
    expect(err.err()).toEqual(Some("err"));
    

    Returns Option<E>

expect

  • expect(msg: string): T
  • Returns the contained Ok value, consuming the self value.

    Panics

    Panics if the value is an Err, with a panic message including the passed message, and the content of the Err.

    Example

    expect(Ok("ok").expect("Testing expect")).toEqual("ok");
    
    try {
        Err("fail result").expect("Testing expect")
    } catch (e: unknown) {
        expect((e as Error).message).toEqual("Testing expect");
    }
    

    Parameters

    • msg: string

    Returns T

expectErr

  • expectErr(msg: string): E
  • Returns the contained Err value, consuming the self value.

    Panics

    Panics if the value is an Ok, with a panic message including the passed message, and the content of the Ok.

    Parameters

    • msg: string

    Returns E

flatten

  • Converts from Result<Result<T, E>, E> to Result<T, E>

    Example

    expect(Ok(Ok(50)).flatten()).toEqual(Ok(50));
    expect(Ok(50).flatten().unwrap()).toEqual(50);
    
    expect(Ok(Err("Error")).flatten()).toEqual(Err("Error"));
    expect(Err("Error").flatten()).toEqual(Err("Error"));
    

    Returns Result<T, E>

isErr

  • isErr(): boolean
  • Returns true if the result is Err.

    Returns boolean

isOk

  • isOk(): boolean
  • Returns true if the result is Ok.

    Returns boolean

map

  • map<U, F>(fn: F): Result<U, E>
  • Maps a Result<T, E> to Result<U, E> by applying a function to a contained Ok value, leaving an Err value untouched. This function can be used to compose the results of two functions.

    Example

    const x: Result<number, string> = Err("5");
    expect(x.map((item) => item * 5)).toEqual(Err("5"));
    
    const y: Result<number, string> = Ok(5);
    expect(y.map((item) => item * 5)).toEqual(Ok(25));
    

    Type parameters

    • U

    • F: (data: T) => U

    Parameters

    • fn: F

    Returns Result<U, E>

mapErr

  • mapErr<F>(fn: (err: E) => F): Result<T, F>
  • Maps a Result<T, E> to Result<T, F> by applying a function to a contained Err value, leaving an Ok value untouched.

    This function can be used to pass through a successful result while handling an error.

    Examples

    const stringify = (x: number) => `error code: ${x}`;
    
    const x: Result<number, number> = Ok(2);
    expect(x.mapErr(stringify)).toEqual(Ok(2));
    
    const y: Result<number, number> = Err(13);
    expect(y.mapErr(stringify)).toEqual(Err("error code: 13"));
    

    Type parameters

    • F

    Parameters

    • fn: (err: E) => F
        • (err: E): F
        • Parameters

          • err: E

          Returns F

    Returns Result<T, F>

mapOr

  • mapOr<U, F>(defaultValue: U, fn: F): U
  • Applies a function to the contained value (if Ok), or returns the provided default (if Err).

    Arguments passed to mapOr are eagerly evaluated; if you are passing the result of a function call, it is recommended to use map_or_else, which is lazily evaluated.

    Example

    const x = new Ok("foo");
    expect(x.mapOr(42 as number, (v) => v.length)).toEqual(3);
    
    const y = new Err("bar");
    expect(y.mapOr(42 as number, (v) => v.length)).toEqual(42);
    

    Type parameters

    • U

    • F: (data: T) => U

    Parameters

    • defaultValue: U
    • fn: F

    Returns U

mapOrElse

  • mapOrElse<U>(defaultFn: (err: E) => U, fn: (data: T) => U): U
  • Maps a Result<T, E> to U by applying a function to a contained Ok value, or a fallback function to a contained Err value.

    This function can be used to unpack a successful result while handling an error.

    Example

    const x: Result<string, string> = new Ok("fOo");
    expect(
        x.mapOrElse(
            (err) => err.toLowerCase(),
            (v) => v.toUpperCase(),
        ),
    ).toEqual("FOO");
    
    const y: Result<string, string> = Err("BaR");
    expect(
        y.mapOrElse(
            (err) => err.toLowerCase(),
            (v) => v.toUpperCase(),
        ),
    ).toEqual("bar");
    

    Type parameters

    • U

    Parameters

    • defaultFn: (err: E) => U
        • (err: E): U
        • Parameters

          • err: E

          Returns U

    • fn: (data: T) => U
        • (data: T): U
        • Parameters

          • data: T

          Returns U

    Returns U

match

  • match<Ok, Err>(__namedParameters: ResultMatch<T, E, Ok, Err>): null | Ok | Err
  • Pattern match to retrieve the value

    Type parameters

    • Ok

      return type of the Ok branch

    • Err

      return type of the Err branch

      Example

      expect(Ok("ok").match({
              ok: some => some.length,
              err: () => "error",
      })).toEqual(2);
      
      expect(Err("error").match({
              ok: _ => "ok",
              err: _ => "Something bad wrong",
      })).toEqual("Something bad wrong")
      
      expect(Err({ code: 404 }).match({  err: err => err.code })).toEqual(404);
      expect(Ok("nice").match({  err: _ => "not nice" })).toBeNull();
      

    Parameters

    • __namedParameters: ResultMatch<T, E, Ok, Err>

    Returns null | Ok | Err

ok

  • Converts from Result<T, E> to Option<T>.

    Converts self into an Option<T>, consuming self, and discarding the error, if any.

    Example

    const ok = Ok("ok");
    expect(ok.ok()).toEqual(Some("ok"));
    
    const err = Err("err");
    expect(err.ok()).toEqual(None());
    

    Returns Option<T>

toString

  • toString(): string
  • Returns a string representation of an object.

    override

    Example

    expect(Err(5).toString()).toEqual(`Err(5)`);
    expect(Err(Err("Error")).toString()).toEqual(`Err(Err(Error))`);
    
    expect(Ok(5).toString()).toEqual("Ok(5)");
    expect(Ok(Ok(5)).toString()).toEqual("Ok(Ok(5))");
    
    // BUT
    expect(Err({ code: 15 }).toString()).toEqual("Err([object Object])");
    

    Returns string

transpose

  • Transposes a Result of an Option into an Option of a Result.

    Ok(None) will be mapped to None. Ok(Some(_)) and Err(_) will be mapped to Some(Ok(_)) and Some(Err(_)).

    Panics

    Panics if the value is an Ok where self is not an Option, with a panic message provided by the Ok's value.

    Example

    const x: Result<Option<number>, string> = Ok(Some(5));
    const y: Option<Result<number, string>> = Some(Ok(5));
    
    expect(x.transpose()).toEqual(y);
    

    Returns Option<Result<T, E>>

unwrap

  • unwrap(): T
  • Returns the contained Ok value, consuming the self value.

    Because this function may panic, its use is generally discouraged. Instead, prefer to use pattern matching and handle the Err case explicitly, or call unwrap_or, unwrap_or_else, or unwrap_or_default.

    Panics

    Panics if the value is an Err, with a panic message provided by the Err's value.

    Example

    expect(Ok(5).unwrap()).toEqual(5);
    expect(Ok([1, 3, 4]).unwrap()).toEqual([1, 3, 4]);
    
    expect(
        Err({
            msg: "Random text",
            code: 15,
        }).unwrap,
    ).toThrow(Error);
    

    Returns T

unwrapErr

  • unwrapErr(): E
  • Returns the contained Err value, consuming the self value.

    Panics

    Panics if the value is an Ok, with a custom panic message provided by the Ok's value.

    Example

    expect(Ok(5).unwrapErr).toThrow(Error);
    
    expect(
        Err({
            msg: "Random text",
            code: 15,
        }).unwrapErr(),
    ).toEqual({
        msg: "Random text",
        code: 15,
    });
    

    Returns E

unwrapOr

  • unwrapOr(defaultVal: T): T
  • Returns the contained Ok value or a provided default.

    Arguments passed to unwrap_or are eagerly evaluated; if you are passing the result of a function call, it is recommended to use unwrap_or_else, which is lazily evaluated.

    Example

    expect(
        Ok({
            test: true,
        }).unwrapOr({ test: false }),
    ).toEqual({
        test: true,
    });
    
    expect(Err(5).unwrapOr({ test: false })).toEqual({
        test: false,
    });
    

    Parameters

    • defaultVal: T

    Returns T

unwrapOrElse

  • unwrapOrElse<F>(fn: F): T
  • Returns the contained Ok value or computes it from a closure.

    Example

    expect(Ok("OK").unwrapOrElse(() => "OK")).toEqual("OK");
    expect(Err("Error").unwrapOrElse(() => "Else")).toEqual("Else");
    

    Type parameters

    • F: () => T

    Parameters

    • fn: F

    Returns T

Generated using TypeDoc