The Maybe class represents an optional value: every Maybe is either Just and contains a value, or Nothing, and contains no value. This is a safer alternative to using null or undefined.

Example

// Creating a Maybe with a value
const justNumber = Maybe.just(42);

// Creating a Maybe with no value
const noValue = Maybe.nothing<string>();

Type Parameters

  • V

Constructors

Properties

isValueOk: bool
value: V

Methods

  • Returns true if the Maybe contains a value (is Just).

    Returns bool

    True if Maybe contains a value, false otherwise

    Example

    const maybe = Maybe.just("hello");
    if (maybe.isJust()) {
    // Safe to unwrap
    console.log(maybe.unwrap()); // Prints "hello"
    }
  • Returns true if the Maybe contains no value (is Nothing).

    Returns bool

    True if Maybe contains no value, false otherwise

    Example

    const maybe = Maybe.nothing<string>();
    if (maybe.isNothing()) {
    // Handle empty case
    console.log("No value present");
    }
  • Extracts the value from the Maybe if it exists. Throws an error if the Maybe contains Nothing.

    Returns V

    The contained value

    Example

    const maybe = Maybe.just(42);
    const value = maybe.unwrap(); // Returns 42

    const nothing = Maybe.nothing<number>();
    nothing.unwrap(); // Throws Error: "Called unwraped on a Nothing value"

    Throws

    If the Maybe contains Nothing

  • Returns the contained value or a provided default value if the Maybe is Nothing.

    Parameters

    • orValue: V

      The default value to return if Maybe is Nothing

    Returns V

    The contained value or the default value

    Example

    const maybe = Maybe.just(42);
    const value1 = maybe.unwrapOr(0); // Returns 42

    const nothing = Maybe.nothing<number>();
    const value2 = nothing.unwrapOr(0); // Returns 0
  • Creates a new Maybe containing the provided value (Just).

    Type Parameters

    • T

    Parameters

    • value: T

      The value to wrap in a Maybe

    Returns Maybe<T>

    A new Maybe instance containing the value

    Example

    const just = Maybe.just("hello");
    just.isJust(); // Returns true
    just.unwrap(); // Returns "hello"
  • Creates a new Maybe with no value (Nothing).

    Type Parameters

    • T

    Returns Maybe<T>

    A new Maybe instance containing Nothing

    Example

    const nothing = Maybe.nothing<string>();
    nothing.isNothing(); // Returns true