Options
All
  • Public
  • Public/Protected
  • All
Menu

An abstract class representing an optional value. There are only two concrete classes extending this one: Some and None.

Some-values contain an internal value while None-values represent the absence of a given value. What makes these two types useful is that they both offer the same API to the consumer.

This means that you can have a function that returns an Optional and you can use the returned values right away without having to check what type the are or if they're valid in one way or another.

For example:

// with this we can pull values out of objects without knowing if they exist or not
function getProperty(obj, propName) {
  if (typeof obj[propName] !== 'undefined' && obj[propName] !== null) {
    return Optional.some(obj[propName]);
  }
  return Optional.none();
}

const data = getSomeData();                  // maybe we don't know what this looks like
getProperty(data, 'c').forEach(console.log); // if c exists pass it to console.log
                                             // otherwise don't do anything

getProperty(data, 'username')
  .map(x => `Hello, ${x}`) // if username exists, map it to an Option containing a greeting
  .forEach(console.log);   // if we just created a greeting, console.log it

Type parameters

  • T

    The type of the value contained within this Optional.

Hierarchy

Index

Methods

Abstract and

  • Compares two Optional values. Returns other if this Optional is a Some; otherwise returns None. This allows chained comparison of Optional values.

    const one = Optional.some(1);
    const two = Optional.some(2);
    
    const twoAgain = one.and(two);
    // twoAgain.isSome() === true
    // twoAgain.unwrap() === 2
    
    const three = Optional.none();
    const four = Optional.some(4);
    
    const fourAgain = three.and(four);
    // fourAgain.isSome() === false

    Type parameters

    • U

      The type of the value contained in the other Optional.

    Parameters

    Returns Optional<U>

    other if this Optional is a Some, otherwise returns None.

Abstract ap

  • Applies the function contained in the Optional func to the value contained within this Optional. The return value is wrapped in a new Optional and returned.

    If func is a None a new None is returned.

    const makeDivider = x => {
      if (x === 0) {
       return Optional.none();
      }
      const divider = y => y / x;
      return Optional.some(divider);
    };
    
    const div2 = makeDivider(2);  // a Some containing the divider function
    const div0 = makeDivider(0);  // a None, because we can't safely divide by 0
    
    const two = Optional.some(2);
    
    const one = two.ap(div2);
    // one.unwrapOr(5) === 1
    
    const three = two.ap(div0);
    // three.unwrapOr(5) === 5

    Type parameters

    • U

      The return type of the function in func and the type of the value contained in the returned Optional.

    Parameters

    Returns Optional<U>

    The return value of func wrapped in a new Optional.

Abstract filter

  • filter(condition: function): Optional<T>
  • Filters an Optional based on the given condition function.

    const one = Optional.some(1);
    
    const greaterThanZero = one.filter(x => x > 0);
    // greaterThanZero.isSome() === true
    // greaterThanZero.unwrap() === 1
    
    const lessThanZero = one.filter(x => x < 0);
    // lessThanZero.isSome() === false

    Parameters

    • condition: function

      A function returning true or false based on this Optional's inner value.

        • (val: T): boolean
        • Parameters

          • val: T

          Returns boolean

    Returns Optional<T>

    this Optional if it is a Some and if condition returns true, otherwise returns a None.

Abstract flatMap

  • flatMap<U>(func: function): Optional<U>
  • Returns a None value if this Optional is a None; otherwise calls func and returns the result.

    This function behaves similarly to map except that in this function func returns an Optional. This means flatMap doesn't auto-wrap the return value from func while map does.

    const square = x => Optional.some(x * x);
    const nothing = () => Optional.none();
    
    const two = Optional.some(2);
    const sixteen = two.flatMap(square).flatMap(square);
    // sixteen.isSome() === true
    // sixteen.unwrap() === 16
    
    const none = Optional.none();
    const result = none.flatMap(square).flatMap(square);
    // result.isSome() === false
    
    const resultAgain = two.flatMap(nothing).flatMap(square);
    // resultAgain.isSome() === false

    Note:

    This function is sometimes also called andThen in other libraries.

    Type parameters

    • U

      The type of the value inside the returned Optional.

    Parameters

    • func: function

      The function to call with this Optional's inner value.

    Returns Optional<U>

    A None if this Optional is a None; otherwise passes this Optional's inner value to func and returns the resulting Optional.

Abstract forEach

  • forEach(func: function): void
  • Calls func with the contained value if this Optional is a Some; otherwise does nothing.

    let val = 0;
    
    const one = Optional.some(1);
    one.forEach(x => { val = x; });
    // val === 1
    
    val = 0;
    
    const two = Optional.none();
    two.forEach(x => { val = x; });
    // val === 0

    Note:

    This function is intended for causing side-effects and therefore does not return anything. If you need a return value, consider using match instead.

    Parameters

    • func: function

      A function to call if this Optional is a Some. This Optional's inner value is passed to func if it is called.

        • (val: any): void
        • Parameters

          • val: any

          Returns void

    Returns void

Abstract forceUnwrap

  • forceUnwrap(message?: undefined | string): T
  • Returns the value contained by this Optional if it is a Some; throws an error if this Optional is a None (because it cannot be unwrapped).

    This function will always print a console warning because it is inherently dangerous to use.

    const one = Optional.some(1);
    console.log(one.forceUnwrap()); // will always console.warn()
    
    const two = Optional.none();
    console.log(two.forceUnwrap()); // will throw because two is a `None`

    Note

    It is usually more ergonomic to unwrap an Optional with unwrapOr or to conditionally do something with the contained value with map or a similar function instead of using forceUnwrap.

    However, there are cases where forceUnwrap may be useful. With that in mind, please note: this function will always print a tupperware:force_unwrap_warning regardless of whether or not the Optional in question is a Some.

    throws

    A tupperware:force_unwrap_on_none if this function is called on a None.

    tupperware:force_unwrap_on_none

    The only way to avoid this is to not call this function on a None. This means you must either know for certain that the Optional in question is a Some, or you must verify it manually with isSome or a similar function.

    Parameters

    • Optional message: undefined | string

      An optional message to be included in the error that this function may throw.

    Returns T

    The value contained within this Optional.

Abstract isNone

  • isNone(): boolean
  • Checks whether or not the given Optional is a None,

    const one = Optional.some(1);
    if (one.isNone()) { // always going to be false.
      // ...
    }
    
    const two = Optional.none();
    if (two.isNone()) { // always going to be true.
      // ...
    }

    Returns boolean

    true if this Optional is a None, otherwise returns false.

Abstract isSome

  • isSome(): boolean
  • Checks whether or not the given Optional is a Some.

    const one = Optional.some(1);
    if (one.isSome()) { // always going to be true.
      // ...
    }
    
    const two = Optional.none();
    if (two.isSome()) { // always going to be false.
      // ...
    }

    Returns boolean

    true if this Optional is a Some, otherwise returns false.

Abstract map

  • Maps an Optional<T> to an Optional<U> by applying func to the value contained in this Optional.

    If this Optional is a Some, the returned value will be the return of func wrapped in a new Optional (resulting in a new Some value); otherwise the returned value will be a new None.

    const one = Optional.some(1);
    const two = one.map(x => x * 2);
    // two.unwrapOr(3) === 2
    
    const three = Optional.none();
    const six = three.map(x => x * 2);
    // six.unwrapOr(7) === 7

    Note:

    If the return value of func is null or undefined, the Optional that is returned is guaranteed to be a None.

    Type parameters

    • U

      Both the return type of func and the type of the value contained in the returned Optional.

    Parameters

    • func: function

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

        • (val: T): U
        • Parameters

          • val: T

          Returns U

    Returns Optional<U>

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

Abstract match

  • match<U, V>(options: OptMatch<T, U, V>): U | V
  • Calls the appropriate function in options and returns the result. If this Optional is a Some, options.some is called with its inner value; otherwise options.none is called.

    const one = Optional.some(1);
    
    const doubled = one.match({
      some: (val) => val * 2, // double it
      none: () => 0,          // we'll pretend `None` implies a 0
    });
    // doubled === 2
    
    const two = Optional.none();
    
    const tripled = two.match({
      some: (val) => val * 3, // tripple it
      none: () => 0,          // again, `None` implies a 0
    });
    
    // tripled === 0

    Note:

    See the OptMatch interface for more details on the structure allowed.

    Type parameters

    • U

      The type of the return value in the case where this Optional is a Some.

    • V

      The type of the return value in the case where this Optional is a None.

    Parameters

    Returns U | V

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

Abstract or

  • Compares two Optional values. Returns this Optional if it is a Some value; otherwise returns the other Optional.

    const one = Optional.some(1);
    const none = Optional.none();
    
    const either = one.or(none);
    // either.isSome() === true
    // either.unwrap() === 1
    
    const eitherAgain = none.or(one);
    // eitherAgain.isSome() === true
    // eitherAgain.unwrap() === 1

    Parameters

    Returns Optional<any>

    this if it is a Some, otherwise returns other.

Abstract orElse

  • Returns this Optional if it is a Some; otherwise calls func and returns the result.

    const one = Optional.some(1);
    const none = Optional.none();
    
    const either = one.orElse(() => none);
    // either.isSome() === true
    // either.unwrap() === 1
    
    const eitherAgain = none.orElse(() => one);
    // eitherAgain.isSome() === true
    // eitherAgain.unwrap() === 1

    Note:

    The argument func will not be evaluated unless this Optional is a None. 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

    Returns Optional<any>

    this Optional if it is a Some, otherwise func's return value is returned.

Abstract toArray

  • toArray(): Array<T>
  • Converts an Optional into an array of either one or no values depending on whether or not this Optional is a Some.

    const one = Optional.some(1);
    let data = one.toArray();
    // data.length === 1
    // data[0] === 1
    
    const nope = Optional.none();
    data = nope.toArray();
    // data.length === 0

    Returns Array<T>

    an array containing this Optional's inner value if it is a Some; otherwise an empty array.

Abstract toString

  • toString(): string
  • Returns None() if this Optional is a None, returns Some( val ) if it is a Some.

    const one = Optional.some(1);
    console.log(one.toString()); // Some( 1 )
    
    const two = Optional.none();
    console.log(two.toString()); // None()

    Returns string

    A string representation of this Optional.

Abstract unwrap

  • unwrap(message?: undefined | string): T
  • Returns the value contained by this Optional if it is a Some; throws an error if this Optional is a None (because it cannot be unwrapped).

    The only safe way to call this function is to first make sure that this Optional is a Some (by calling isSome or isNone).

    const one = Optional.some(1);
    
    if (one.isSome()) {
      console.log(one.unwrap()); // will not throw; we know it's safe to call `unwrap`
    }
    
    // however:
    const two = Optional.none();
    
    if (two.isSome()) {
      console.log(two.unwrap()); // won't run b/c two is a `None`
    } else {
      console.log(two.unwrap()); // will throw; two is a `None` so it can't be `unwrap`ed
    }
    throws

    A tupperware:unwrap_on_none error if you attempted to call this function on a None value.

    tupperware:unwrap_on_none:

    To avoid this issue, either make sure that your logic is correct concerning whether or not you should be unwrap-ing this value or use unwrapOr instead which allows you to specify a default value to fall back on in the case where this Optional is a None.

    Parameters

    • Optional message: undefined | string

      An optional message to be included in the error that this function may throw.

    Returns T

    The value contained within this Optional.

Abstract unwrapOr

  • unwrapOr(other: T | function): T
  • Returns the value contained by this Optional if it is a Some, otherwise returns other as a fallback.

    Here other can be either the fallback value itself, or a function that returns that value. If it is a function, other will not be evaluated unless it this Optional is a None.

    const maybeOne = Optional.some(1);
    const one = maybeOne.unwrapOr(3); // one === 1
    const oneAgain = maybeOne.unwrapOr(() => 5); // one === 1
    
    const maybeTwo = Optional.none();
    const two = maybeTwo.unwrapOr(3); // two === 3
    const twoAgain = maybeTwo.unwrapOr(() => 5); // two === 5

    Parameters

    • other: T | function

      A default value to fall back on if this Optional is a None. Can be the default itself, or a function that returns the default.

    Returns T

    The value in this Optional if it is a Some, otherwise returns other.

Abstract unwrapOrElse

  • unwrapOrElse(func: function): T
  • Returns the value contained by this Optional if it is a Some, otherwise calls func and returns the result.

    const maybeOne = Optional.some(1);
    const one = maybeOne.unwrapOrElse(() => 3); // one === 1
    
    const maybeTwo = Optional.none();
    const two = maybeTwo.unwrapOrElse(() => 3); // two === 3

    Note

    The argument func will not be evaluated unless this Optional is a None. 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 Optional is a None.

        • (): T
        • Returns T

    Returns T

    The value in this Optional if it is a Some, otherwise returns the return value of func.

Static fromNullable

  • Creates an Optional with the given value. If null or undefined is provided a None will be returned, otherwise a Some containing the given value will be returned.

    const one = Optional.fromNullable(1);     // one.unwrapOr(0) === 1
    const none = Optional.fromNullable(null); // none.unwrapOr(0) === 0
    const nope = Optional.fromNullable();     // nope.unwrapOr(0) === 0

    Type parameters

    • A

      The type of the value that the new Optional will contain.

    Parameters

    • Optional value: A

      The value to create an Optional with.

    Returns Optional<A>

    Either a Some or a None depending on the value provided.

Static none

Static of

  • Creates an Some with the given value.

    const one = Optional.of(1);
    // one.unwrapOr(0) === 1

    Type parameters

    • A

      The type of the value that the new Some will contain.

    Parameters

    • value: A

      A value to create a Some with.

    Returns Optional<A>

    A Some instance containing value.

Static some

  • Creates a Some with the given value.

    const one = Optional.some(1);
    // one.unwrapOr(0) === 1

    Type parameters

    • A

      The type of the value that the new Some will contain.

    Parameters

    • value: A

      A value to create a Some with.

    Returns Optional<A>

    A Some 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