Skip to main content

index

@ts-rust/std


@ts-rust/std / Option

Option

The Option module provides utilities for handling optional values in a type-safe manner. Inspired by Rust's Option type, this module offers the Option and PendingOption types to represent values that may or may not be present (Some or None). It includes type definitions for Option, PendingOption, and related error types, as well as utility functions for creating and checking Option instances. Use this module to avoid null/undefined errors and write more explicit, safer TypeScript code.

Enumerations

EnumerationDescription

OptionErrorKind

Enumerates error codes specific to Option operations.

These codes are used in OptionError instances thrown by methods like unwrap or expect when operations fail due to the state of the option.

Classes

ClassDescription

OptionError

An error thrown by Option methods when operations fail due to the option's state or unexpected conditions.

This class extends AnyError with error kinds specific to Option operations, as defined in OptionErrorKind. It is typically thrown by methods like unwrap, expect, or others that enforce strict access or behavior on Some or None variants. Use it to handle failures gracefully in a type-safe manner, inspecting the OptionErrorKind to determine the cause.

Example

const opt = none<number>();
try {
opt.unwrap();
} catch (e) {
expect(e).toBeInstanceOf(OptionError);
expect(e.kind).toBe(OptionErrorKind.UnwrapCalledOnNone);
expect(e.message).toBe("`unwrap`: called on `None`");
}

Interfaces

InterfaceDescription

Optional

Interface defining the core functionality of an Option, inspired by Rust's Option type, with additional methods tailored for TypeScript.

Represents a value that may or may not be present, offering a robust alternative to null or undefined. It includes most Rust Option methods (e.g., map, andThen, unwrap) for safe value handling, plus TypeScript-specific extensions like toPending and async variants of and with Promise support.

For methods accepting predicates (e.g., orElse, filter, map, andThen), exceptions in the provided function result in None, ensuring predictable, type-safe behavior. If error handling is a concern, use okOr or okOrElse to convert to a Result.

Implementations like Some and None enable pattern matching, transformations, and error handling in a type-safe way.

PendingOption

Interface defining an asynchronous Option that wraps a Promise resolving to an Option.

Extends Option functionality for pending states, with methods mirroring their synchronous counterparts but returning PendingOption or Promise for async operations. Rejections typically resolve to None unless otherwise specified.

Type Aliases

Type AliasDescription

None

Represents an empty Option with no value.

Unlike Some, it does not provide a value property.

Option

A type that represents either a value (Some\<T\>) or no value (None\<T\>).

Inspired by Rust's Option, it is used to handle values that may or may not be present, avoiding null or undefined checks. This is a union of Some and None variants.

SettledOption

A synchronous Option where the contained value T is guaranteed to be non-PromiseLike, ensuring immediate availability without awaiting.

This restricted Option variant enforces synchronous values for methods like insert, getOrInsert, and getOrInsertWith, which mutate the option. Use it when you need a type-safe, synchronous option.

Some

Represents an Option containing a value of type T.

Functions

FunctionDescription

isOption

Checks if a value is an Option, narrowing its type to Option<unknown>.

This type guard verifies whether the input conforms to the Optional interface, indicating it is either a Some or None.

Example

const x: unknown = some(42);
const y: unknown = none<number>();
const z: unknown = "not an option";

expect(isOption(x)).toBe(true);
expect(isOption(y)).toBe(true);
expect(isOption(z)).toBe(false);

if (isOption(x)) {
expect(x.isSome()).toBe(true); // Type narrowed to Option<unknown>
}

isOptionError

Checks if a value is an OptionError, narrowing its type if true.

isPendingOption

Checks if a value is a PendingOption, narrowing its type to PendingOption<unknown>.

This type guard verifies whether the input is a PendingOption, indicating it wraps a Promise resolving to an Option (either Some or None).

Example

const x: unknown = pendingOption(some(42));
const y: unknown = pendingOption(none<number>());
const z: unknown = some(42); // Not a PendingOption

expect(isPendingOption(x)).toBe(true);
expect(isPendingOption(y)).toBe(true);
expect(isPendingOption(z)).toBe(false);

if (isPendingOption(x)) {
expect(await x).toStrictEqual(some(42)); // Type narrowed to PendingOption<unknown>
}

none

Creates a None variant of an Option, representing the absence of a value.

Produces an option indicating no value is present.

Example

const x = none<number>();

expect(x.isNone()).toBe(true);
expect(() => x.expect("x is `None`")).toThrow("x is `None`");

pendingNone

Creates a PendingOption\<T\> that resolves to None.

Produces a pending option representing the absence of a value, with the type resolved to Awaited for consistency with asynchronous operations.

Example

const x = pendingNone<number>();

expect(await x).toStrictEqual(none());
expect((await x).isNone()).toBe(true);

pendingOption

Creates a PendingOption\<T\> from an option, promise, or factory function.

Accepts an Option, a Promise resolving to an Option, or a function returning either, and converts it into a pending option, handling asynchronous resolution as needed.

Example

const x = pendingOption(some(42));
const y = pendingOption(() => Promise.resolve(none<string>()));
const z = pendingOption(async () => some("thing"));

expect(await x).toStrictEqual(some(42));
expect(await y).toStrictEqual(none());
expect(await z).toStrictEqual(some("thing"));

pendingSome

Creates a PendingOption\<T\> that resolves to Some containing the awaited value.

Takes a value or a promise and wraps its resolved result in a Some, ensuring the value type is Awaited to handle any PromiseLike input.

Example

const x = pendingSome(42);
const y = pendingSome(Promise.resolve("hello"));

expect(await x).toStrictEqual(some(42));
expect(await y).toStrictEqual(some("hello"));

some

Creates a Some variant of an Option containing the given value.

Wraps the provided value in a Some, indicating the presence of a value.

Example

const x = some(42);

expect(x.isSome()).toBe(true);
expect(x.expect("Not 42")).toBe(42);