Options
All
  • Public
  • Public/Protected
  • All
Menu

Type Option represents an optional value: every Option is either Some and contains a value, or None, and does not. Option types are very common in Rust code, as they have a number of uses:

  • Initial values
  • Return value for otherwise reporting simple errors, where None is returned on error
  • Optional struct fields
  • Optional function arguments
  • Nullable values
  • Swapping things out of difficult situations

Type parameters

  • T

Hierarchy

  • Option

Implements

Index

Methods

Private and

  • Returns None if the option is None, otherwise returns optb.

    Type parameters

    • U

    Parameters

    Returns Option<U>

andThen

  • andThen<U, F>(fn: F): Option<U>
  • Returns None if the option is None, otherwise calls f with the wrapped value and returns the result.

    Some languages call this operation flatmap.

    Example

    const some = Some(25); const sq = (x: number) => Some(x * x);
    
    // 25 * 25 => 625 + 5 => 630
    const result = some.andThen(sq).andThen((x) => Some(x + 5));
    expect(result.unwrap()).toEqual(630);
    

    Type parameters

    Parameters

    • fn: F

    Returns Option<U>

clone

  • Returns Option<T>

Private cloneInnerValue

  • cloneInnerValue(): T
  • Returns T

expect

  • expect(msg: string): T
  • Returns the contained Some value, consuming the self value.

    Panics

    Panics if the value is a None with a custom panic message provided by msg. [Error]

    Parameters

    • msg: string

    Returns T

filter

  • filter<P>(predicate: P): Option<T>
  • 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.

    Example

    const result = Some({ status: 200 })
        .filter((item) => item.status === 200)
        .map((_) => "Ok")
        .unwrapOr("Error");
    
    expect(result).toEqual("Ok");
    
    expect(Some(200).filter((item) => item === 200).unwrapOr(500)).toEqual(200);
    

    Type parameters

    • P: (data: T) => boolean

    Parameters

    • predicate: P

    Returns Option<T>

flatten

  • Converts from Option<Option> to Option

    Example

    expect(Some(Some(Some(50))).flatten()).toEqual(Some(Some(50)));
    expect(Some(Some(50)).flatten()).toEqual(Some(50));
    
    expect(Some(50).flatten()).toEqual(Some(50));
    expect(Some(50).flatten().unwrap()).toEqual(50);
    
    expect(Some(None()).flatten()).toEqual(None());
    expect(None().flatten()).toEqual(None());
    

    Returns Option<T>

isNone

  • isNone(): boolean
  • Returns true if the option is a None value.

    Returns boolean

isSome

  • isSome(): boolean
  • Returns true if the option is a Some value.

    Returns boolean

map

  • Maps an Option<T> to Option<U> by applying a function to a contained value.

    Example

    const mappedSome = Some({ isSome: true }).map(item => ({ data: !item.isSome }));
    
    expect(mappedSome.unwrap()).toEqual({ data: false });
    

    Type parameters

    • U

    • F: (data: T) => U

    Parameters

    • fn: F

    Returns Option<U>

mapOr

  • mapOr<U, F>(defaultVal: U, fn: F): U
  • Applies a function to the contained value (if any), or returns the provided default (if not).

    Example

    const defaultStatus: number = 500;
    
    const some = Some({ status: 200 });
    const mappedSome = some.mapOr(defaultStatus, (data) => data.status);
    expect(mappedSome).toEqual(200);
    

    Type parameters

    • U

    • F: (data: T) => U

    Parameters

    • defaultVal: U
    • fn: F

    Returns U

mapOrElse

  • mapOrElse<U, D, F>(defaultFn: D, fn: F): U
  • Applies a function to the contained value (if any), or computes a default (if not).

    Example

    const defaultStatus: number = 500;
    
    const some = Some({ status: 200 });
    const mappedSome = some.mapOrElse(() => defaultStatus, (data) => data.status);
    expect(mappedSome).toEqual(200);
    
    const none = None();
    const mappedNone = none.mapOrElse(() => defaultStatus, (data) => data.status);
    expect(mappedNone).toEqual(500);
    

    Type parameters

    • U

    • D: () => U

    • F: (data: T) => U

    Parameters

    • defaultFn: D
    • fn: F

    Returns U

match

  • match<Some, None>(__namedParameters: OptionMatch<T, Some, None>): null | Some | None
  • Pattern match to retrieve the value

    Type parameters

    • Some

      return type of the Some branch

    • None

      return type of the None branch

      Example

      expect(Some("ok").match({
              some: some => some.length,
              none: () => "error",
      })).toEqual(2);
      
      expect(None().match({
              some: _ => "some",
              none: () => "Something bad wrong",
      })).toEqual("Something bad wrong")
      
      expect(None().match({
              some: _ => 200,
              none: () => 404,
      })).toEqual(404)
      

    Parameters

    • __namedParameters: OptionMatch<T, Some, None>

    Returns null | Some | None

okOr

  • okOr<E>(err: E): Result<T, E>
  • Transforms the Option<T> into a Result<T, E>, mapping Some(v) to Ok(v) and None to Err(err).

    Arguments passed to okOr are eagerly evaluated; if you are passing the result of a function call, it is recommended to use okOrElse, which is lazily evaluated.

    Example

    expect(Some(5).okOr("Failed")).toEqual(Ok(5));
    expect(None().okOr("Failed")).toEqual(Err("Failed"));
    

    Type parameters

    • E

    Parameters

    • err: E

    Returns Result<T, E>

okOrElse

  • okOrElse<E, F>(fn: F): Ok<T> | Err<E>
  • Transforms the Option<T> into a Result<T, E>, mapping Some(v) to Ok(v) and None to Err(err()).

    Example

    const failFn = () => "Failed";
    
    expect(Some(5).okOrElse(failFn)).toEqual(Ok(5));
    expect(None().okOrElse(failFn)).toEqual(Err("Failed"));
    

    Type parameters

    • E

    • F: () => E

    Parameters

    • fn: F

    Returns Ok<T> | Err<E>

replace

  • replace(value: T): Option<T>
  • Replaces the actual value in the option by the value given in parameter, returning the old value if present, leaving a Some in its place without deinitializing either one.

    Example

    expect(Some(50).unwrap()).toEqual(50);
    
    const oldSome = some.replace(250); expect(oldSome.unwrap()).toEqual(50);
    expect(some.unwrap()).toEqual(250);
    

    Parameters

    • value: T

    Returns Option<T>

toString

  • toString(): string
  • Returns a string representation of an object.

    override

    Example

    expect(None().toString()).toEqual("None");
    
    expect(Some(5).toString()).toEqual("Some(5)");
    expect(Some(Some(5)).toString()).toEqual("Some(Some(5))");
    
    // BUT
    expect(Some({ code: 15 }).toString()).toEqual("Some([object Object])");
    

    Returns string

transpose

  • Transposes an Option of a Result into a Result of an Option.

    None will be mapped to Ok(None). Some(Ok(_)) and Some(Err(_)) will be mapped to Ok(Some(_)) and Err(_).

    Panics Panics if the value is an Some where self is not an Result,

    with a panic message provided by the Some's value.

    Example

    const x: Result<Option<number>, string> = Ok(Some(5));
    const y: Option<Result<number, string>> = Some(Ok(5));
    
    expect(x).toEqual(y.transpose());
    

    Type parameters

    • E: unknown

    Returns Result<Option<T>, E>

unsafe_insert

  • unsafe_insert(val: T): Option<T>
  • Inserts value into the option

    If the option already contains a value, the old value is dropped.

    unsafe

    Example

    expect(None().unsafe_insert(5)).toEqual(Some(5));
    expect(Some(0).unsafe_insert(65)).toEqual(Some(65));
    

    Parameters

    • val: T

    Returns Option<T>

unwrap

  • unwrap(): T
  • Returns the contained Some value, consuming the self value.

    Panics

    Panics if the self value equals None. [TypeError]

    Example

    expect(Some(5).unwrap()).toEqual(5);
    expect(Some([1, 3, 4]).unwrap()).toEqual([1, 3, 4]);
    expect(None().unwrap).toThrow(TypeError);
    

    Returns T

unwrapOr

  • unwrapOr(defaultVal: T): T
  • Returns the contained Some value or a provided default.

    Example

    const some = Some("SOME");
    expect(some.unwrapOrElse(() => "NONE")).toEqual("SOME");
    

    Parameters

    • defaultVal: T

    Returns T

unwrapOrElse

  • unwrapOrElse<F>(fn: F): T
  • Returns the contained Some value or computes it from a closure.

    Example

    expect(None().unwrapOrElse(() => "NONE")).toEqual("NONE");
    

    Type parameters

    • F: () => T

    Parameters

    • fn: F

    Returns T

zip

  • Zips self with another Option.

    If self is Some(s) and other is Some(o), this method returns Some((s, o)). Otherwise, None is returned.

    Example

    const x = Some(1);
    const y = Some("hi");
    const z = None();
    
    expect(x.zip(y)).toEqual(Some([1, "hi"])); expect(x.zip(z)).toEqual(None());
    

    Type parameters

    • U

    Parameters

    Returns Option<[T, U]>

Static makeDefault

  • makeDefault(): Option<unknown>
  • Returns the "default value" for a Option => None.

    Returns Option<unknown>

Generated using TypeDoc