Class Optional<T>

A special type that encourages the move away from null and undefined.

An Optional is immutable and is a wrapper type of T | null | undefined that provides useful functions for transformation and safe retrieval of an optional value.

Type Parameters

  • T

    type of the value within this optional.

Properties

optValue: OptionalValue<T>

Accessors

  • get get(): OptionalValue<T>
  • Get the value contained within the optional. The value is returned without any checks, so it might be null or undefined.

    Returns OptionalValue<T>

  • get hasValue(): boolean
  • Returns true if this optional is not empty, false otherwise.

    Returns boolean

  • get isEmpty(): boolean
  • Returns true if this optional is empty, false otherwise

    Returns boolean

Methods

  • Utility for checking equality against the value contained within this optional

    Parameters

    • other: T

      value to check against

    Returns boolean

    true if this optional is this value

  • If there's a value, returns the result of applying a predicate on the value contained within this optional, or false when no value exists.

    Parameters

    • predicate: ((value) => boolean)

      function that test the value

        • (value): boolean
        • Parameters

          • value: T

          Returns boolean

    Returns boolean

    false if this optional is empty or the result of applying the predicate

  • Same as map, but the transformation must return an optional. Does nothing if this optional is empty.

    Type Parameters

    • U

    Parameters

    Returns Optional<U>

    an optional with the transformation potentially applied

  • Returns the value contained within this optional if it exists or returns a default value supplied.

    Parameters

    • defaultValue: T

      value returned if this optional is empty

    Returns T

    the value contained or default supplied.

  • Apply a transformation on the value contained within this optional. Does nothing if this optional is empty.

    Type Parameters

    • U

    Parameters

    • transformer: ((value) => U)

      a transformation function

        • (value): U
        • Parameters

          • value: T

          Returns U

    Returns Optional<U>

    an optional with the transformation potentially applied

  • Returns this optional if it has a value or an alternative provided optional

    Parameters

    Returns Optional<T>

    this or alternative

  • Checks that a value is neither null nor undefined.

    Has the added benefit of type narrowing in typescript.

    Type Parameters

    • U

    Parameters

    Returns opt is U

    true if the value is neither undefined or null

  • Parameters

    • value: unknown

      checks if a value is an Optional

    Returns value is Optional<unknown>

Generated using TypeDoc