happy-rusty
    Preparing search index...

    Interface Option<T>

    Type Option represents an optional value: every Option is either Some and contains a value, or None, and does not. This interface includes methods that act on the Option type, similar to Rust's Option enum.

    As Rust Code:

    pub enum Option<T> {
    None,
    Some(T),
    }
    interface Option<T> {
        "[OptionKindSymbol]": "Some" | "None";
        "[toStringTag]": "Option";
        "[iterator]"(): Iterator<T>;
        and<U>(other: Option<U>): Option<U>;
        andThen<U>(fn: (value: T) => Option<U>): Option<U>;
        andThenAsync<U>(
            fn: (value: T) => AsyncLikeOption<U> | Option<U>,
        ): AsyncOption<U>;
        eq(other: Option<T>): boolean;
        expect(msg: string): T;
        filter(predicate: (value: T) => boolean): Option<T>;
        flatten<U>(this: Option<Option<U>>): Option<U>;
        inspect(fn: (value: T) => void): this;
        isNone(): boolean;
        isNoneOr(predicate: (value: T) => boolean): boolean;
        isNoneOrAsync(
            predicate: (value: T) => boolean | PromiseLike<boolean>,
        ): Promise<boolean>;
        isSome(): boolean;
        isSomeAnd(predicate: (value: T) => boolean): boolean;
        isSomeAndAsync(
            predicate: (value: T) => boolean | PromiseLike<boolean>,
        ): Promise<boolean>;
        map<U>(fn: (value: T) => U): Option<U>;
        mapOr<U>(defaultValue: U, fn: (value: T) => U): U;
        mapOrElse<U>(defaultFn: () => U, fn: (value: T) => U): U;
        okOr<E>(error: E): Result<T, E>;
        okOrElse<E>(err: () => E): Result<T, E>;
        or(other: Option<T>): Option<T>;
        orElse(fn: () => Option<T>): Option<T>;
        orElseAsync(fn: () => Option<T> | AsyncLikeOption<T>): AsyncOption<T>;
        reduce<U, R = T | U>(
            other: Option<U>,
            fn: (value: T, otherValue: U) => R,
        ): Option<T | U | R>;
        toString(): string;
        transpose<U, E>(this: Option<Result<U, E>>): Result<Option<U>, E>;
        unwrap(): T;
        unwrapOr(defaultValue: T): T;
        unwrapOrElse(fn: () => T): T;
        unwrapOrElseAsync(fn: () => T | PromiseLike<T>): Promise<Awaited<T>>;
        unzip<U, R>(this: Option<[U, R]>): [Option<U>, Option<R>];
        xor(other: Option<T>): Option<T>;
        zip<U>(other: Option<U>): Option<[T, U]>;
        zipWith<U, R>(
            other: Option<U>,
            fn: (value: T, otherValue: U) => R,
        ): Option<R>;
    }

    Type Parameters

    • T

      The type of the value contained in the Some variant.

    Hierarchy (View Summary)

    Index

    Properties

    "[OptionKindSymbol]": "Some" | "None"

    A unique symbol property used to identify the variant of this Option. Returns 'Some' if the Option contains a value, or 'None' if it represents absence.

    This is used internally by the isOption utility function to verify that an object is a valid Option instance, and to distinguish between Some and None variants without calling methods.

    Note: The symbol itself is not exported as part of the public API. Use the isOption utility function or the isSome()/isNone() methods for type checking.

    "[toStringTag]": "Option"

    The well-known symbol Symbol.toStringTag used by Object.prototype.toString(). Returns 'Option' so that Object.prototype.toString.call(option) produces '[object Option]'.

    This enables reliable type identification even across different execution contexts (e.g., iframes, different module instances).

    const x = Some(5);
    console.log(Object.prototype.toString.call(x)); // '[object Option]'

    Methods

    • Implements the Iterator protocol, allowing Option to be used with for...of loops and spread syntax.

      • For Some(value), yields the contained value once.
      • For None, yields nothing (empty iterator).

      This is similar to Rust's Option::iter() method.

      Returns Iterator<T>

      An iterator that yields zero or one value.

      // Using with for...of
      for (const value of Some(5)) {
      console.log(value); // 5
      }

      for (const value of None) {
      console.log(value); // never executed
      }

      // Using with spread operator
      const arr1 = [...Some(5)]; // [5]
      const arr2 = [...None]; // []

      // Using with Array.from
      Array.from(Some('hello')); // ['hello']
      Array.from(None); // []
    • Returns None if the Option is None, otherwise returns other. This is sometimes called "and then" because it is similar to a logical AND operation.

      Type Parameters

      • U

        The type of the value in the other Option.

      Parameters

      • other: Option<U>

        The Option to return if this is Some.

      Returns Option<U>

      None if this is None, otherwise returns other.

      • or
      • xor
      const x = Some(2);
      const y = Some('hello');
      console.log(x.and(y).unwrap()); // 'hello'

      const z = None;
      console.log(z.and(y).isNone()); // true
    • Returns None if the Option is None, otherwise calls fn with the wrapped value and returns the result. This function can be used for control flow based on Option values.

      Type Parameters

      • U

        The type of the value returned by the function.

      Parameters

      • fn: (value: T) => Option<U>

        A function that takes the contained value and returns an Option.

      Returns Option<U>

      The result of fn if this is Some, otherwise None.

      • map
      • orElse
      const x = Some(2);
      const result = x.andThen(v => v > 0 ? Some(v * 2) : None);
      console.log(result.unwrap()); // 4

      const y = None;
      console.log(y.andThen(v => Some(v * 2)).isNone()); // true
    • Asynchronous version of andThen.

      Type Parameters

      • U

        The type of the value returned by the function.

      Parameters

      • fn: (value: T) => AsyncLikeOption<U> | Option<U>

        A function that takes the contained value and returns PromiseLike<Option<U>> or Option<U>.

      Returns AsyncOption<U>

      A promise that resolves to None if this is None, otherwise the result of fn.

      • andThen
      • orElseAsync
      const x = Some(2);
      const result = await x.andThenAsync(async v => Some(v * 2));
      console.log(result.unwrap()); // 4
    • Tests whether this and other are both Some containing equal values, or both are None. This method can be used for comparing Option instances in a value-sensitive manner.

      Parameters

      • other: Option<T>

        The other Option to compare with.

      Returns boolean

      true if this and other are both Some with equal values, or both are None, otherwise false.

      const a = Some(5);
      const b = Some(5);
      const c = Some(10);
      console.log(a.eq(b)); // true
      console.log(a.eq(c)); // false
      console.log(None.eq(None)); // true
      console.log(a.eq(None)); // false
    • Returns the contained Some value, with a provided error message if the value is a None.

      Parameters

      • msg: string

        The error message to provide if the value is a None.

      Returns T

      Throws an error with the provided message if the Option is a None.

      unwrap

      const x = Some(5);
      console.log(x.expect('value should exist')); // 5

      const y = None;
      y.expect('value should exist'); // throws TypeError: value should exist
    • Returns None if the Option is None, otherwise calls predicate with the wrapped value and returns:

      • Some(t) if predicate returns true (where t is the wrapped value), and
      • None if predicate returns false.

      Parameters

      • predicate: (value: T) => boolean

        A function that takes the contained value and returns a boolean.

      Returns Option<T>

      const x = Some(4);
      console.log(x.filter(v => v > 2).isSome()); // true
      console.log(x.filter(v => v > 5).isNone()); // true
    • Converts from Option<Option<U>> to Option<U>.

      Type Parameters

      • U

        The type of the value contained in the inner Option.

      Parameters

      Returns Option<U>

      None if the Option is None, otherwise returns the contained Option.

      const x = Some(Some(5));
      console.log(x.flatten().unwrap()); // 5

      const y = Some(None);
      console.log(y.flatten().isNone()); // true
    • Calls the provided function with the contained value if this is Some. This is primarily for side effects and does not transform the Option.

      Parameters

      • fn: (value: T) => void

        A function to call with the contained value.

      Returns this

      this, unmodified, for chaining additional methods.

      const x = Some(5);
      // Prints "value: 5" and returns Some(10)
      const doubled = x.inspect(v => console.log('value:', v)).map(v => v * 2);

      const y = None;
      // Does nothing and returns None
      y.inspect(v => console.log('value:', v));
    • Returns true if the Option is a None value.

      Returns boolean

      const x = Some(2);
      console.log(x.isNone()); // false

      const y = None;
      console.log(y.isNone()); // true
    • Returns true if the Option is None, or the predicate returns true for the contained value.

      Parameters

      • predicate: (value: T) => boolean

        A function that takes the contained value and returns a boolean.

      Returns boolean

      isSomeAnd

      const x = Some(2);
      console.log(x.isNoneOr(v => v > 1)); // true
      console.log(x.isNoneOr(v => v > 5)); // false

      const y = None;
      console.log(y.isNoneOr(v => v > 5)); // true (always true for None)
    • Asynchronous version of isNoneOr.

      Parameters

      • predicate: (value: T) => boolean | PromiseLike<boolean>

        A function that takes the contained value and returns a PromiseLike<boolean> or boolean.

      Returns Promise<boolean>

      A promise that resolves to true if the Option is None or the predicate resolves to true.

      isNoneOr

      const x = Some(2);
      await x.isNoneOrAsync(async v => v > 1); // true

      const y = None;
      await y.isNoneOrAsync(async v => v > 5); // true
    • Returns true if the Option is a Some value.

      Returns boolean

      const x = Some(2);
      console.log(x.isSome()); // true

      const y = None;
      console.log(y.isSome()); // false
    • Returns true if the Option is a Some value and the predicate returns true for the contained value.

      Parameters

      • predicate: (value: T) => boolean

        A function that takes the contained value and returns a boolean.

      Returns boolean

      const x = Some(2);
      console.log(x.isSomeAnd(v => v > 1)); // true
      console.log(x.isSomeAnd(v => v > 5)); // false
    • Asynchronous version of isSomeAnd.

      Parameters

      • predicate: (value: T) => boolean | PromiseLike<boolean>

        A function that takes the contained value and returns a PromiseLike<boolean> or boolean.

      Returns Promise<boolean>

      A promise that resolves to true if the Option is Some and the predicate resolves to true.

      isSomeAnd

      const x = Some(2);
      await x.isSomeAndAsync(async v => v > 1); // true
    • Maps an Option<T> to Option<U> by applying a function to a contained value.

      Type Parameters

      • U

        The type of the value returned by the map function.

      Parameters

      • fn: (value: T) => U

        A function that takes the contained value and returns a new value.

      Returns Option<U>

      andThen

      const x = Some(5);
      console.log(x.map(v => v * 2).unwrap()); // 10

      const y = None;
      console.log(y.map(v => v * 2).isNone()); // true
    • Maps an Option<T> to U by applying a function to the contained value (if any), or returns the provided default (if not).

      Type Parameters

      • U

        The type of the value returned by the map function or the default value.

      Parameters

      • defaultValue: U

        The value to return if the Option is None.

      • fn: (value: T) => U

        A function that takes the contained value and returns a new value.

      Returns U

      mapOrElse

      const x = Some(5);
      console.log(x.mapOr(0, v => v * 2)); // 10

      const y = None;
      console.log(y.mapOr(0, v => v * 2)); // 0
    • Maps an Option<T> to U by applying a function to a contained value (if any), or computes a default (if not).

      Type Parameters

      • U

        The type of the value returned by the map function or the default function.

      Parameters

      • defaultFn: () => U

        A function that returns the default value.

      • fn: (value: T) => U

        A function that takes the contained value and returns a new value.

      Returns U

      mapOr

      const x = Some(5);
      console.log(x.mapOrElse(() => 0, v => v * 2)); // 10

      const y = None;
      console.log(y.mapOrElse(() => 0, v => v * 2)); // 0
    • Transforms the Option<T> into a Result<T, E>, mapping Some(v) to Ok(v) and None to Err(err).

      Type Parameters

      • E

        The type of the error value in the Err variant of the resulting Result.

      Parameters

      • error: E

        The error value to use if the Option is a None.

      Returns Result<T, E>

      okOrElse

      const x = Some(5);
      console.log(x.okOr('error').isOk()); // true

      const y = None;
      console.log(y.okOr('error').unwrapErr()); // 'error'
    • Transforms the Option<T> into a Result<T, E>, mapping Some(v) to Ok(v) and None to Err(err()).

      Type Parameters

      • E

        The type of the error value in the Err variant of the resulting Result.

      Parameters

      • err: () => E

        A function that returns the error value.

      Returns Result<T, E>

      okOr

      const x = None;
      console.log(x.okOrElse(() => 'error').unwrapErr()); // 'error'
    • Returns the Option if it contains a value, otherwise returns other. This can be used for providing a fallback Option.

      Parameters

      • other: Option<T>

        The fallback Option to use if this is None.

      Returns Option<T>

      this if it is Some, otherwise other.

      • and
      • xor
      • reduce
      const x = None;
      const y = Some(5);
      console.log(x.or(y).unwrap()); // 5

      const z = Some(2);
      console.log(z.or(y).unwrap()); // 2
    • Returns the Option if it contains a value, otherwise calls fn and returns the result. This method can be used for lazy fallbacks, as fn is only evaluated if this is None.

      Parameters

      • fn: () => Option<T>

        A function that produces an Option.

      Returns Option<T>

      this if it is Some, otherwise the result of fn.

      andThen

      const x = None;
      const result = x.orElse(() => Some(10));
      console.log(result.unwrap()); // 10

      const y = Some(5);
      console.log(y.orElse(() => Some(10)).unwrap()); // 5
    • Asynchronous version of orElse.

      Parameters

      Returns AsyncOption<T>

      A promise that resolves to this if it is Some, otherwise the result of fn.

      • orElse
      • andThenAsync
      const x = None;
      const result = await x.orElseAsync(async () => Some(10));
      console.log(result.unwrap()); // 10
    • Reduces two Option values into one using the provided function.

      • If both this and other are Some, applies fn to both values and returns Some(result).
      • If only this is Some, returns Some(this_value).
      • If only other is Some, returns Some(other_value).
      • If both are None, returns None.

      This is similar to Rust's Option::reduce with Into<R> constraints. In TypeScript, when only one Option is Some, that value is returned as-is (relying on TypeScript's structural typing for compatibility with R).

      Type Parameters

      • U

        The type of the value in the other Option.

      • R = T | U

        The result type (defaults to T | U).

      Parameters

      • other: Option<U>

        The other Option to reduce with.

      • fn: (value: T, otherValue: U) => R

        A function that combines both values when both are Some.

      Returns Option<T | U | R>

      The reduced Option.

      • zip
      • zipWith
      • or
      const a = Some(10);
      const b = Some(20);
      console.log(a.reduce(b, (x, y) => x + y).unwrap()); // 30

      const c = None as Option<number>;
      console.log(a.reduce(c, (x, y) => x + y).unwrap()); // 10
      console.log(c.reduce(b, (x, y) => x + y).unwrap()); // 20
      console.log(c.reduce(c, (x, y) => x + y).isNone()); // true

      // With different types that share a common supertype
      const str = Some('hello');
      const num = Some(42);
      const result: Option<string> = str.reduce(num, (s, n) => `${s}-${n}`);
    • Custom toString implementation that uses the Option's contained value.

      Returns string

      console.log(Some(5).toString()); // 'Some(5)'
      console.log(None.toString()); // 'None'
    • Transposes an Option of a Result into a Result of an Option.

      Type Parameters

      • U

        The type of the success value in the Ok variant of the Result.

      • E

        The type of the error value in the Err variant of the Result.

      Parameters

      Returns Result<Option<U>, E>

      Ok containing Some if the Option is a Some containing Ok, Err containing the error if the Option is a Some containing Err, Ok containing None if the Option is None.

      const x = Some(Ok(5));
      console.log(x.transpose().unwrap().unwrap()); // 5

      const y = Some(Err('error'));
      console.log(y.transpose().unwrapErr()); // 'error'

      const z: Option<Result<number, string>> = None;
      console.log(z.transpose().unwrap().isNone()); // true
    • Returns the contained Some value.

      Returns T

      Throws an error if the value is a None.

      • expect
      • unwrapOr
      const x = Some(5);
      console.log(x.unwrap()); // 5

      const y = None;
      y.unwrap(); // throws TypeError
    • Returns the contained Some value or a provided default.

      Parameters

      • defaultValue: T

        The value to return if the Option is a None.

      Returns T

      unwrapOrElse

      const x = Some(5);
      console.log(x.unwrapOr(10)); // 5

      const y = None;
      console.log(y.unwrapOr(10)); // 10
    • Returns the contained Some value or computes it from a closure.

      Parameters

      • fn: () => T

        A function that returns the default value.

      Returns T

      unwrapOr

      const x = None;
      console.log(x.unwrapOrElse(() => 10)); // 10
    • Asynchronous version of unwrapOrElse.

      Parameters

      • fn: () => T | PromiseLike<T>

        A function that returns PromiseLike<T> or T as the default value.

      Returns Promise<Awaited<T>>

      A promise that resolves to the contained value or the result of the function.

      unwrapOrElse

      const x = None;
      await x.unwrapOrElseAsync(async () => 10); // 10
    • Converts from Option<[U, R]> to [Option<U>, Option<R>]. If this is Some([a, b]), returns [Some(a), Some(b)]. If this is None, returns [None, None].

      Type Parameters

      • U

        The type of the first value in the tuple.

      • R

        The type of the second value in the tuple.

      Parameters

      Returns [Option<U>, Option<R>]

      A tuple of Options, one for each element in the original Option of a tuple.

      zip

      const x = Some([1, 'hello'] as [number, string]);
      const [a, b] = x.unzip();
      console.log(a.unwrap()); // 1
      console.log(b.unwrap()); // 'hello'
    • Returns Some if exactly one of this, other is Some, otherwise returns None. This can be thought of as an exclusive or operation on Option values.

      Parameters

      • other: Option<T>

        The other Option to compare with.

      Returns Option<T>

      Some if exactly one of this and other is Some, otherwise None.

      • and
      • or
      const x = Some(2);
      const y = None;
      console.log(x.xor(y).unwrap()); // 2

      const a = Some(2);
      const b = Some(3);
      console.log(a.xor(b).isNone()); // true
    • Combines this with another Option by zipping their contained values. If this is Some(s) and other is Some(o), returns Some([s, o]). If either this or other is None, returns None.

      Type Parameters

      • U

        The type of the value in the other Option.

      Parameters

      • other: Option<U>

        The other Option to zip with.

      Returns Option<[T, U]>

      An Option containing a tuple of the values if both are Some, otherwise None.

      • zipWith
      • unzip
      • reduce
      const x = Some(1);
      const y = Some('hello');
      console.log(x.zip(y).unwrap()); // [1, 'hello']

      const z = None;
      console.log(x.zip(z).isNone()); // true
    • Zips this with another Option using a provided function to combine their contained values. If this is Some(s) and other is Some(o), returns Some(fn(s, o)). If either this or other is None, returns None.

      Type Parameters

      • U

        The type of the value in the other Option.

      • R

        The return type of the combining function.

      Parameters

      • other: Option<U>

        The other Option to zip with.

      • fn: (value: T, otherValue: U) => R

        The function to combine the values from both Options.

      Returns Option<R>

      An Option containing the result of fn if both Options are Some, otherwise None.

      • zip
      • reduce
      const x = Some(2);
      const y = Some(3);
      console.log(x.zipWith(y, (a, b) => a * b).unwrap()); // 6