Options
All
  • Public
  • Public/Protected
  • All
Menu

An abstract class representing the result of some computation (that may have failed). There are only two concrete classes extending this one: Ok and Err.

Ok-values represent a computation result that returned successfully while Err-values represent a failed computation. Similar to Optional's Some and None, these two types are useful because they share the same API.

This means you could have a function that returns a Result and use the value straight away without having to do a bunch of type checking to determine what happened during the computation.

For example:

// with this we can parse an integer out of a string and never have to check for `NaN`s again
function safeParseInt(val) {
  const parsed = Number.parseInt(val, 10);
  if (Number.isNan(parsed)) {
    return Result.err(`Failed to parse an integer from the string "${val}".`);
  }
  return Result.ok(parsed);
}

const num = getSomeNumber();                  // maybe this returns a string (for some reason)
const parsed = safeParseInt(num).unwrapOr(0); // if it parsed properly, we can get the value
                                              // but if it didn't we'll just default back to 0

// or if we want to be more explicit (or do more complex things)
const parsed = safeParseInt(num).match({
  ok: (val) => { return val; },      // this function will be called if we got an `Ok` back
  err: (e) => {                      // and this one will be called if we got an `Err` back
     console.error(e);
     return computeSomethingElse();
  },
});

Type parameters

  • T

    The type of the value contained within this Result if it is an Ok value.

  • E

    The type of the value contained within this Result if it is an Err value.

Hierarchy

Index

Methods

Abstract flatMap

  • flatMap<U>(func: function): Result<U, E>
  • Returns an Err if this Result is an Err; otherwise calls func and returns the result.

    This function behaves similarly to map and mapErr except that in this function, func returns a Result. This means flatMap doesn't auto-wrap the return value from func while map and mapErr both do.

    const square = x => Result.ok(x * x);
    const error = () => Result.err('it broke!');
    
    const two = Result.ok(2);
    const sixteen = two.flatMap(square).flatMap(square);
    // sixteen.isOk() === true
    // sixteen.unwrap() === 16
    
    const parseError = Result.err('parsing error');
    const result = parseError.flatMap(square).flatMap(square);
    // result.isOk() === false
    // result.unwrap() === 'parsing error'
    
    const resultAgain = two.flatMap(error).flatMap(square);
    // resultAgain.isOk() === false
    // resultAgain.unwrap() === 'it broke!'

    Note:

    This function is sometimes called andThen in other libraries.

    Type parameters

    • U

      The type of the inner value contained in func's return value (if this Result is an Ok.

    Parameters

    • func: function

      The function to call with this Result's inner value (if it is an Ok).

        • Parameters

          • ok: T

          Returns Result<U, E>

    Returns Result<U, E>

    An Err if this Result is an Err; otherwise passes this Result's inner value to func and returns the resulting Result.

Abstract getErr

  • Tries to return the internal Err value of this Result. Returns a Some containing the value if it is an Err, returns a None if it is an Ok.

    You can also think of this function as transforming a Result into an Optional, where the Some comes from the Err and the Ok (if it exists) is thrown away.

    const one = Result.err('parsing error');
    const maybeOne = one.getErr();
    
    // maybeOne.isSome() === true
    // maybeOne.unwrap() === 'parsing error'
    
    const one = Result.ok(1);
    const maybeOne = one.getErr();
    
    // maybeOne.isNone() === true

    Returns Optional<E>

    A Some containing this Result's value if it is an Err, otherwise returns a None.

Abstract getOk

  • Tries to return the internal Ok value of this Result. Returns a Some containing the value if it is an Ok, returns a None if it is an Err.

    You can also think of this function as transforming a Result into an Optional, where the Some comes from the Ok and the Err (if it exists) is thrown away.

    const one = Result.ok(1);
    const maybeOne = one.getOk();
    
    // maybeOne.isSome() === true
    // maybeOne.unwrap() === 1
    
    const one = Result.err('parsing error');
    const maybeOne = one.getOk();
    
    // maybeOne.isNone() === true

    Returns Optional<T>

    A Some containing this Result's value if it is an Ok, otherwise returns a None.

Abstract isErr

  • isErr(): boolean
  • Checks whether or not the given Result is an Err.

    const one = Result.err(1);
    // one.isErr() === true

    Returns boolean

    true if this Result is an Err, otherwise returns false.

Abstract isOk

  • isOk(): boolean
  • Checks whether or not the given Result is an Ok.

    const one = Result.ok(1);
    // one.isOk() === true

    Returns boolean

    true if this Result is an Ok, otherwise returns false.

Abstract map

  • map<U>(func: function): Result<U, E>
  • Maps a Result<T, E> to an Result<U, E> by applying func to the value contained in this Result.

    If this Result is an Ok, the returned value will be the return of func wrapped in a new Result (resulting in a new Ok); otherwise the returned value will be a new Err.

    const maybeOne = Result.ok(1);
    const maybeTwo = maybeOne.map(x => x * 2);
    // maybeTwo.isOk() === true
    // maybeTwo.unwrap() === 2
    
    const maybeThree = Result.err(1);
    const maybeSix = maybeThree.map(x => x * 2);
    // maybeSix.isErr() === true
    // maybeSix.unwrapErr() === 1

    Type parameters

    • U

      Both the return type of func and the type contained in the new Ok returned by map (unless map returns an Err).

    Parameters

    • func: function

      A function to apply to this Result's contained value.

        • (val: T): U
        • Parameters

          • val: T

          Returns U

    Returns Result<U, E>

    The return value of func wrapped up as a new Result.

Abstract mapErr

  • mapErr<F>(func: function): Result<T, F>
  • Maps a Result<T, E> to an Result<T, F> by applying func to the value contained in this Result.

    If this Result is an Err, the returned value will be the return of func wrapped in a new Result (resulting in a new Err); otherwise the returned value will be a new Ok.

    const maybeOne = Result.ok(1);
    const maybeTwo = maybeOne.mapErr(x => x * 2);
    // maybeTwo.isOk() === true
    // maybeTwo.unwrap() === 1
    
    const maybeThree = Result.err(2);
    const maybeSix = maybeThree.mapErr(x => x * 2);
    // maybeSix.isErr() === true
    // maybeSix.unwrapErr() === 4

    Type parameters

    • F

      Both the return type of func and the type contained in the new Err returned by map (unless map returns an Ok).

    Parameters

    • func: function

      A function to apply to this Result's contained value.

        • (val: E): F
        • Parameters

          • val: E

          Returns F

    Returns Result<T, F>

    The return value of func wrapped up as a new Result.

Abstract match

  • Calls the appropriate function in options and returns the result. If this Result is an Ok, options.ok is called; otherwise options.err is called.

    const maybeOne = Result.ok(1);
    
    const doubled = maybeOne.match({
      ok: (val) => val * 2, // double it
      err: (err) => 0,      // we'll pretend an Err implies a 0
    });
    
    // doubled === 2
    
    const maybeTwo = Result.err(2);
    
    const tripled = maybeTwo.match({
      ok: (val) => val * 3,
      err: (err) => 0,
    });
    
    // tripled === 0

    Note:

    See ResultMatch for more details on the structure allowed.

    Type parameters

    • U

      The type of the return value in the case where this Result is an Ok.

    • F

      The type of the return value in the case where this Result is an Err.

    Parameters

    Returns U | F

    The return value from whichever function specified in options is called.

Abstract orElse

  • orElse(func: function): Result<T, any>
  • Returns this Result if it is an Ok; otherwise calls func and returns the result.

    const okay = Result.ok(1);
    const error = Result.err('parseError');
    
    const either = okay.orElse(() => error);
    // either.isOk() === true
    // either.unwrap() === 1
    
    const eitherAgain = error.orElse(() => okay);
    // eitherAgain.isOk() === true
    // eitherAgain.unwrap() === 1

    Note

    The argument func will not be evaluated unless this Result is an Err. This means orElse is ideal for cases when you need to fall back on a value that needs to be computed (and may be expensive to compute).

    Parameters

    • func: function

      A function returning an alternate Result if this one is an Err.

        • Parameters

          • err: E

          Returns Result<T, any>

    Returns Result<T, any>

    this Result if it is an Ok, otherwise func's return value is returned.

Abstract toString

  • toString(): string
  • Returns Ok( val ) if this Result is an Ok, returns Err( err ) if it is an Err.

    const one = Result.ok(1);
    // one.toString() === "Ok( 1 )"
    
    const two = Result.err(2);
    // two.toString() === "Err( 2 )"

    Returns string

    A string representation of this Result.

Abstract unwrap

  • unwrap(message?: undefined | string): T
  • Returns the value contained by this Result if it is an Ok. Throws an error containing message if it is an Err or a default message if none is provided.

    const maybeOne = Result.ok(1);
    // this won't throw because it's an `Ok` value.
    const one = maybeOne.unwrap("couldn't unwrap an Ok");
    
    // but:
    const maybeOne = Result.err('parsing error');
    // this will throw because it's an `Err` value.
    const one = maybeOne.unwrap("couldn't unwrap an Ok");

    Parameters

    • Optional message: undefined | string

      A message to use in the thrown error if this Result is an Err.

    Returns T

    This Result's contained value if it is an Ok.

Abstract unwrapErr

  • unwrapErr(message?: undefined | string): E
  • Returns the value contained by this Result if it is an Err. Throws an error containing message if it is an Ok or a default message if none is provided.

    const maybeError = Result.ok(1);
    // this will throw because it's an `Ok` value.
    const error = maybeError.unwrapErr("couldn't unwrap an Err");
    
    // but:
    const maybeError = Result.err('parsing error');
    // this won't throw because it's an `Err` value.
    const error = maybeError.unwrapErr("couldn't unwrap an Err");

    Parameters

    • Optional message: undefined | string

      A message to use in the thrown error if this Result is an Ok.

    Returns E

    This Result's contained value if it is an Err.

Abstract unwrapOr

  • unwrapOr(other: T): T
  • Returns the value contained by this Result if it is an Ok, otherwise returns other as a default value.

    const maybeOne = Result.ok(1);
    const one = maybeOne.unwrapOr(2);
    // one === 1
    
    const maybeOne = Result.err('parse error');
    const one = maybeOne.unwrapOr(2);
    // one === 2

    Parameters

    • other: T

      A default value to fall back on if this Result is an Err.

    Returns T

    The value in this Result if it is an Ok, otherwise returns other.

Abstract unwrapOrElse

  • unwrapOrElse(func: function): T
  • Returns the value contained by this Result if it is an Ok, otherwise calls func with the Err value and returns the result.

    const maybeOne = Result.ok(1);
    const one = maybeOne.unwrapOrElse((err) => err.length);
    // one === 1
    
    const maybeOne = Result.err('parse error');
    const one = maybeOne.unwrapOrElse((err) => err.length);
    // one === 11

    Note

    The argument func will not be evaluated unless this Result is an Err. This means unwrapOrElse is ideal for cases when you need to fall back on a value that needs to be computed (and may be expensive to compute).

    Parameters

    • func: function

      A function returning the fall-back value if this Result is an Err.

        • (err: E): T
        • Parameters

          • err: E

          Returns T

    Returns T

    The value in this Result if it is an Ok, otherwise returns the return value of func.

Static err

  • err<F>(error: F): Result<any, F>
  • Creates an Err with the given value.

    const one = Result.err(1);
    // one.unwrapErr() === 1

    Type parameters

    • F

      The type of value that the new Err will contain.

    Parameters

    • error: F

      The value with which to create the Err instance.

    Returns Result<any, F>

    An Err instance containing value.

Static ok

  • ok<U>(value: U): Result<U, any>
  • Creates an Ok with the given value.

    const one = Result.ok(1);
    // one.unwrap() === 1

    Type parameters

    • U

      The type of value that the new Ok will contain.

    Parameters

    • value: U

      The value with which to create the Ok instance.

    Returns Result<U, any>

    An Ok instance containing value.

Legend

  • Module
  • Object literal
  • Variable
  • Function
  • Function with type parameter
  • Index signature
  • Type alias
  • Type alias with type parameter
  • Enumeration
  • Enumeration member
  • Property
  • Method
  • Interface
  • Interface with type parameter
  • Constructor
  • Property
  • Method
  • Index signature
  • Class
  • Class with type parameter
  • Constructor
  • Property
  • Method
  • Accessor
  • Index signature
  • Inherited constructor
  • Inherited property
  • Inherited method
  • Inherited accessor
  • Protected property
  • Protected method
  • Protected accessor
  • Private property
  • Private method
  • Private accessor
  • Static property
  • Static method

Generated using TypeDoc