Skip to main content
Module

x/optionals/mod.ts>Option

Rust-like error handling and options for TypeScript and Deno!
Latest
class Option
Re-export
import { Option } from "https://deno.land/x/optionals@v3.0.0/mod.ts";

A Rust-like Option class.

Note: Please use either Some or None to construct an Option.

Examples

Example 1

function divide(left: number, right: number): Option<number> {
  if (right === 0) return None();

  return Some(left / right);
}

Constructors

new
Option(input: T | none)

A constructor for an Option.

Note: Please use either Some or None to construct Options.

Properties

private
val: T | none
readonly
[Symbol.toStringTag]

Converts Option into a String for display purposes.

Methods

expect(msg: string): T

Returns the contained Some value, consuming the Option. Throws an Error with a given message if the contained value is None.

isNone(): boolean

Returns true if contained value is None.

isSome(): boolean

Returns true if contained value isnt None.

map<U>(fn: (input: T) => U): Option<U>

Maps an Option to Option by applying a function to a contained Some value, leaving None values untouched.

mapOr<U>(fallback: U, fn: (input: T) => U): U

Returns the provided fallback (if None), or applies a function to the contained value.

okOr<E extends Error>(err: E | string): Result<T, E>

Transforms the Option<T> into a Result<T, E>, mapping Some to Ok and None to Err.

or(or: Option<T>): Option<T>

Returns or if the Option is None, otherwise returns self.

peek(): T | none

Returns contained value for use in matching.

Note: Please only use this to match against in if or swtich statments.

Returns the contained Some value, consuming the Option. Throws an Error if contained value is None.

unwrapOr(fallback: T): T

Returns the contained Some value or a provided default.

unwrapOrElse(fn: () => T): T

Returns the contained Some value or computes it from a closure.

Iterator support for Option.

Note: This method will only yeild if the Option is Some.

Static Methods

from<T>(fn: () => T | null | undefined): Option<T>

Run a closure and convert it into an Option. If the function returns null or undefined, an Option containing None will be reutrned.

Note: Please use fromAsync to capture the result of asynchronous closures.

fromAsync<T>(fn: () => Promise<T | null | undefined>): Promise<Option<T>>

Run an asynchronous closure and convert it into an Option. If the function returns null or undefined, an Option containing None will be reutrned.

Note: Please use from to capture the result of synchronous closures.