Skip to main content
Module

x/optionals/mod.ts>Result

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

A Rust-like Result class.

Note: Please use either Ok or Err to construct Results.

Examples

Example 1

function divide(left: number, right: number): Result<number, Error> {
  if (right === 0) return Err("Divided by zero");

  return Ok(left / right);
}

Constructors

new
Result(input: T | E)

A constructor for a Result

Type Parameters

T
E extends Error

Properties

private
val: T | E

Methods

private
formatError(err: Error)
expect(msg: string): T

Returns the contained Ok value, consuming the Result. Throws an Error with a given message if contained value is not Ok.

isErr(): boolean

Returns true if contained value is an error.

isOk(): boolean

Returns true if contained value isnt an error.

map<U>(fn: (input: T) => U): Result<U, E>

Maps a Result<T, E> to Result<U, E> by applying a function to a contained Ok value, leaving an Error value untouched.

mapErr<U extends Error>(fn: (input: E) => U): Result<T, U>

Maps a Result<T, E> to Result<T, U> by applying a function to a contained Error value, leaving an Ok value untouched.

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

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

or(or: Result<T, E>): Result<T, E>

Returns or if the result is Error, otherwise returns self.

peek(): T | E

Returns contained value for use in matching.

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

throw(): void

Throws contained Errors, consuming the Result.

Returns the contained Ok value, consuming the Result. Throws an Error if contained value is not Ok.

Returns the contained Error value, consuming the Result. Throws an Error if contained value is not an Error.

unwrapOr(fallback: T): T

Returns the contained Ok value or a provided default.

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

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

Static Methods

from<T>(fn: (() => T) | (() => Promise<T>)): Promise<Result<T, Error>>

Run a closure in a try/catch and convert it into a Result.

partition<T, E extends Error>(input: Array<Result<T, E>>): { ok: Array<T>; err: Array<E>; }

Partition an array of Results into Ok values and Errors