Skip to main content
Module

x/optionals/mod.ts>Option

Rust-like error handling and options for TypeScript and Deno!
Go to Latest
class Option
Re-export
import { Option } from "https://deno.land/x/optionals@v2.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

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.

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.

Static Methods

from<T>(fn: (() => T) | (() => Promise<T>)): Promise<Option<T>>

Run a closure in a try/catch and convert it into an Option. If the function throws an Error, an Option containing None will be reutrned.