Class Result<V, E>

A Result type that represents either a success (Ok) or failure (Err) state. This is useful for error handling and expressing outcomes that might fail.

Example

// Creating a successful result
const success = Result.ok<string>("data");

// Creating a failed result
const failure = Result.err<string, Error>(new Error("error message"));

// Safely handling both cases
if (success.isOk()) {
const value = success.unwrap(); // "data"
}

Type Parameters

  • V

    The type of the success value

  • E = Error

    The type of the error value, defaults to Error

Constructors

Properties

errValue: null | E
okValue: V

Methods

  • Checks if the Result is Err variant.

    Returns bool

    true if Result is Err, false otherwise

    Example

    const failure = Result.err<number, string>("error");
    if (failure.isErr()) {
    // Safe to unwrapErr
    const error = failure.unwrapErr();
    }
  • Checks if the Result is Ok variant.

    Returns bool

    true if Result is Ok, false otherwise

    Example

    const success = Result.ok<number, string>(42);
    if (success.isOk()) {
    // Safe to unwrap
    const value = success.unwrap();
    }
  • Extracts the success value from a Result if it's an Ok variant.

    Returns V

    The success value

    Throws

    If the Result is Err variant

    Example

    const result = Result.ok<number, string>(42);
    const value = result.unwrap(); // returns 42
  • Extracts the error value from a Result if it's an Err variant.

    Returns E

    The error value

    Throws

    If the Result is Ok variant

    Example

    const result = Result.err<number, string>("invalid input");
    const error = result.unwrapErr(); // returns "invalid input"
  • Returns the success value if Result is Ok, otherwise returns the provided default value. This is a safe way to get a value without throwing an error.

    Parameters

    • orValue: V

      The default value to return if Result is Err

    Returns V

    Either the success value or the provided default

    Example

    const success = Result.ok<number, string>(42);
    const failure = Result.err<number, string>("error");

    success.unwrapOr(0); // returns 42
    failure.unwrapOr(0); // returns 0