/** * Result types to allow for more type-safe handling of errors. * * This is basically a partial reimplementation of the Result type in Rust. * https://doc.rust-lang.org/std/result/enum.Result.html */ interface BaseResult { /** Whether this is Ok */ is_ok: boolean; /** Whether this is Err */ is_err: boolean; /** Calls op if the result is Ok, otherwise returns the Err value of self. */ and_then(op: (val: T) => Ok): Result; and_then(op: (val: T) => Err): Result; and_then(op: (val: T) => Result): Result; and_then(op: (val: T) => Result): Result; /** Maps by applying a function to a contained Ok value, leaving Err untouched. */ map(op: (v: T) => U): Result; /** Maps by applying a function to a contained Err value, leaving Ok untouched. */ map_err(op: (v: E) => F): Result; /** Calls op if the result is Err, otherwise returns the Ok value of self. */ or_else(op: (v: E) => T): Result; /** Returns the contained Ok value or throw an Error for Err. */ unwrap(): T; /** Returns the contained Err value or throw an Error for Ok. */ unwrap_err(): E; /** Returns the contained Ok value or a provided default. */ unwrap_or(d: U): T | U; } /** A successful result. */ export class Ok implements BaseResult { readonly is_ok = true; readonly is_err = false; constructor(readonly value: T) {} and_then(op: (val: T) => Ok): Ok; and_then(op: (val: T) => Err): Result; and_then(op: (val: T) => Result): Result; and_then(op: (val: T) => Result): Result { return op(this.value); } map(op: (v: T) => U): Ok { return new Ok(op(this.value)); } map_err(): this { return this; } or_else(): this { return this; } unwrap(): T { return this.value; } unwrap_err(): never { throw new Error("unwrap_err() called on Ok()."); } unwrap_or(): T { return this.value; } } /** An error result. */ export class Err implements BaseResult { readonly is_ok = false; readonly is_err = true; constructor(readonly error: E) {} and_then(): this { return this; } map(): this { return this; } or_else(op: (v: E) => Result): Result { return op(this.error); } map_err(op: (v: E) => F): Result { return new Err(op(this.error)); } unwrap(): never { throw new Error("unwrap() called on error."); } unwrap_err(): E { return this.error; } unwrap_or(val: U): U { return val; } } /** Result of an operation that might fail */ export type Result = Ok | Err; /** Wrap the value in a successful result. */ export function ok(value: T): Ok { return new Ok(value); } /** Wrap the value in an error result. */ export function err(error: E): Err { return new Err(error); } /** Collect an array of results into a single result. */ export function collect(items: Result[]): Result { const ok_values: T[] = []; for (const r of items) { if (r.is_ok) { ok_values.push(r.value); } else { return r; } } return ok(ok_values); }