import { toString } from './utils.js'; import { Option, None, Some } from './option.js'; import { AsyncResult } from './asyncresult.js'; /* * Missing Rust Result type methods: * pub fn contains(&self, x: &U) -> bool * pub fn contains_err(&self, f: &F) -> bool * pub fn and(self, res: Result) -> Result * pub fn expect_err(self, msg: &str) -> E * pub fn unwrap_or_default(self) -> T */ interface BaseResult extends Iterable { /** `true` when the result is Ok */ isOk(): this is OkImpl; /** `true` when the result is Err */ isErr(): this is ErrImpl; /** * Returns the contained `Ok` value, if exists. Throws an error if not. * * The thrown error's * [`cause'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause) * is set to value contained in `Err`. * * If you know you're dealing with `Ok` and the compiler knows it too (because you tested * `isOk()` or `isErr()`) you should use `value` instead. While `Ok`'s `expect()` and `value` will * both return the same value using `value` is preferable because it makes it clear that * there won't be an exception thrown on access. * * @param msg the message to throw if no Ok value. * * @example * ```typescript * let goodResult = Ok(1); * let badResult = Err(new Error('something went wrong')); * * goodResult.expect('goodResult should be a number'); // 1 * badResult.expect('badResult should be a number'); // throws Error("badResult should be a number - Error: something went wrong") * ``` */ expect(msg: string): T; /** * Returns the contained `Err` value, if exists. Throws an error if not. * @param msg the message to throw if no Err value. * * @example * ```typescript * let goodResult = Ok(1); * let badResult = Err(new Error('something went wrong')); * * goodResult.expectErr('goodResult should not be a number'); // throws Error("goodResult should not be a number") * badResult.expectErr('badResult should not be a number'); // new Error('something went wrong') * ``` */ expectErr(msg: string): E; /** * Returns the contained `Ok` value. * Because this function may throw, its use is generally discouraged. * Instead, prefer to handle the `Err` case explicitly. * * If you know you're dealing with `Ok` and the compiler knows it too (because you tested * `isOk()` or `isErr()`) you should use `value` instead. While `Ok`'s `unwrap()` and `value` will * both return the same value using `value` is preferable because it makes it clear that * there won't be an exception thrown on access. * * Throws if the value is an `Err`, with a message provided by the `Err`'s value and * [`cause'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause) * set to the value. * * @example * ```typescript * let goodResult = new Ok(1); * let badResult = new Err(new Error('something went wrong')); * * goodResult.unwrap(); // 1 * badResult.unwrap(); // throws Error("something went wrong") * ``` */ unwrap(): T; /** * Returns the contained `Err` value. * Because this function may throw, its use is generally discouraged. * Instead, prefer to handle the `Ok` case explicitly and access the `error` property * directly. * * Throws if the value is an `Ok`, with a message provided by the `Ok`'s value and * [`cause'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause) * set to the value. * * @example * ```typescript * let goodResult = new Ok(1); * let badResult = new Err('something went wrong'); * * goodResult.unwrapErr(); // throws an exception * badResult.unwrapErr(); // returns 'something went wrong' * ``` */ unwrapErr(): E; /** * Returns the contained `Ok` value or a provided default. * * (This is the `unwrap_or` in rust) * * @example * ```typescript * let goodResult = Ok(1); * let badResult = Err(new Error('something went wrong')); * * goodResult.unwrapOr(5); // 1 * badResult.unwrapOr(5); // 5 * ``` */ unwrapOr(val: T2): T | T2; /** * Returns the contained `Ok` value or computes a value with a provided function. * * The function is called at most one time, only if needed. * * @example * ``` * Ok('OK').unwrapOrElse( * (error) => { console.log(`Called, got ${error}`); return 'UGH'; } * ) // => 'OK', nothing printed * * Err('A03B').unwrapOrElse((error) => `UGH, got ${error}`) // => 'UGH, got A03B' * ``` */ unwrapOrElse(f: (error: E) => T2): T | T2; /** * Calls `mapper` if the result is `Ok`, otherwise returns the `Err` value of self. * This function can be used for control flow based on `Result` values. * * @example * ```typescript * let goodResult = Ok(1); * let badResult = Err(new Error('something went wrong')); * * goodResult.andThen((num) => new Ok(num + 1)).unwrap(); // 2 * badResult.andThen((num) => new Err(new Error('2nd error'))).unwrap(); // throws Error('something went wrong') * goodResult.andThen((num) => new Err(new Error('2nd error'))).unwrap(); // throws Error('2nd error') * * goodResult * .andThen((num) => new Ok(num + 1)) * .mapErr((err) => new Error('mapped')) * .unwrap(); // 2 * badResult * .andThen((num) => new Err(new Error('2nd error'))) * .mapErr((err) => new Error('mapped')) * .unwrap(); // throws Error('mapped') * goodResult * .andThen((num) => new Err(new Error('2nd error'))) * .mapErr((err) => new Error('mapped')) * .unwrap(); // throws Error('mapped') * ``` */ andThen(mapper: (val: T) => Result): Result; /** * Maps a `Result` to `Result` by applying a function to a contained `Ok` value, * leaving an `Err` value untouched. * * This function can be used to compose the results of two functions. * * @example * ```typescript * let goodResult = Ok(1); * let badResult = Err(new Error('something went wrong')); * * goodResult.map((num) => num + 1).unwrap(); // 2 * badResult.map((num) => num + 1).unwrap(); // throws Error("something went wrong") * ``` */ map(mapper: (val: T) => U): Result; /** * Maps a `Result` to `Result` by applying a function to a contained `Err` value, * leaving an `Ok` value untouched. * * This function can be used to pass through a successful result while handling an error. * * @example * ```typescript * let goodResult = Ok(1); * let badResult = Err(new Error('something went wrong')); * * goodResult * .map((num) => num + 1) * .mapErr((err) => new Error('mapped')) * .unwrap(); // 2 * badResult * .map((num) => num + 1) * .mapErr((err) => new Error('mapped')) * .unwrap(); // throws Error("mapped") * ``` */ mapErr(mapper: (val: E) => F): Result; /** * Maps a `Result` to `Result` by either converting `T` to `U` using `mapper` * (in case of `Ok`) or using the `default_` value (in case of `Err`). * * If `default` is a result of a function call consider using `mapOrElse` instead, it will * only evaluate the function when needed. * * @example * ```typescript * let goodResult = Ok(1); * let badResult = Err(new Error('something went wrong')); * * goodResult.mapOr(0, (value) => -value) // -1 * badResult.mapOr(0, (value) => -value) // 0 * ``` */ mapOr(default_: U, mapper: (val: T) => U): U; /** * Maps a `Result` to `Result` by either converting `T` to `U` using `mapper` * (in case of `Ok`) or producing a default value using the `default` function (in case of * `Err`). * * @example * ```typescript * let goodResult = Ok(1); * let badResult = Err(new Error('something went wrong')); * * goodResult.mapOrElse((_error) => 0, (value) => -value) // -1 * badResult.mapOrElse((_error) => 0, (value) => -value) // 0 * ``` */ mapOrElse(default_: (error: E) => U, mapper: (val: T) => U): U; /** * Returns `Ok()` if we have a value, otherwise returns `other`. * * `other` is evaluated eagerly. If `other` is a result of a function * call try `orElse()` instead – it evaluates the parameter lazily. * * @example * * Ok(1).or(Ok(2)) // => Ok(1) * Err('error here').or(Ok(2)) // => Ok(2) */ or(other: Result): Result; /** * Returns `Ok()` if we have a value, otherwise returns the result * of calling `other()`. * * `other()` is called *only* when needed and is passed the error value in a parameter. * * @example * * Ok(1).orElse(() => Ok(2)) // => Ok(1) * Err('error').orElse(() => Ok(2)) // => Ok(2) */ orElse(other: (error: E) => Result): Result; /** * Converts from `Result` to `Option`, discarding the error if any * * Similar to rust's `ok` method */ toOption(): Option; /** * Creates an `AsyncResult` based on this `Result`. * * Useful when you need to compose results with asynchronous code. */ toAsyncResult(): AsyncResult; } /** * Contains the error value */ export class ErrImpl implements BaseResult { /** * An empty Err * * @example * ```typescript * const x: Result = Err.EMPTY * ``` */ static readonly EMPTY = new ErrImpl(undefined); isOk(): this is OkImpl { return false; } isErr(): this is ErrImpl { return true; } readonly error!: E; private readonly _stack!: string; [Symbol.iterator](): Iterator { return { next(): IteratorResult { return { done: true, value: undefined! }; }, }; } constructor(val: E) { if (!(this instanceof ErrImpl)) { return new ErrImpl(val); } this.error = val; const stackLines = new Error().stack!.split('\n').slice(2); if (stackLines && stackLines.length > 0 && stackLines[0].includes('ErrImpl')) { stackLines.shift(); } this._stack = stackLines.join('\n'); } unwrapOr(val: T2): T2 { return val; } unwrapOrElse(f: (error: E) => T2): T2 { return f(this.error); } expect(msg: string): never { // The cause casting required because of the current TS definition being overly restrictive // (the definition says it has to be an Error while it can be anything). // See https://github.com/microsoft/TypeScript/issues/45167 throw new Error(`${msg} - Error: ${toString(this.error)}\n${this._stack}`, { cause: this.error as any }); } expectErr(_msg: string): E { return this.error; } unwrap(): never { // The cause casting required because of the current TS definition being overly restrictive // (the definition says it has to be an Error while it can be anything). // See https://github.com/microsoft/TypeScript/issues/45167 throw new Error(`Tried to unwrap Error: ${toString(this.error)}\n${this._stack}`, { cause: this.error as any }); } unwrapErr(): E { return this.error; } map(_mapper: unknown): Err { return this; } andThen(op: (val: never) => Result): Result { return this; } mapErr(mapper: (err: E) => E2): Err { return new Err(mapper(this.error)); } mapOr(default_: U, _mapper: unknown): U { return default_; } mapOrElse(default_: (error: E) => U, _mapper: unknown): U { return default_(this.error); } or(other: Ok): Result; or>(other: R): R; or(other: Result): Result { return other; } orElse(other: (error: E) => Result): Result { return other(this.error); } toOption(): Option { return None; } toString(): string { return `Err(${toString(this.error)})`; } get stack(): string | undefined { return `${this}\n${this._stack}`; } toAsyncResult(): AsyncResult { return new AsyncResult(this); } } // This allows Err to be callable - possible because of the es5 compilation target export const Err = ErrImpl as typeof ErrImpl & ((err: E) => Err); export type Err = ErrImpl; /** * Contains the success value */ export class OkImpl implements BaseResult { /** * An empty Ok * * @example * ```typescript * const x: Result = Ok.EMPTY * ``` */ static readonly EMPTY = new OkImpl(undefined); isOk(): this is OkImpl { return true; } isErr(): this is ErrImpl { return false; } readonly value!: T; [Symbol.iterator](): Iterator { return [this.value][Symbol.iterator](); } constructor(val: T) { if (!(this instanceof OkImpl)) { return new OkImpl(val); } this.value = val; } unwrapOr(_val: unknown): T { return this.value; } unwrapOrElse(_f: unknown): T { return this.value; } expect(_msg: string): T { return this.value; } expectErr(msg: string): never { throw new Error(msg); } unwrap(): T { return this.value; } unwrapErr(): never { // The cause casting required because of the current TS definition being overly restrictive // (the definition says it has to be an Error while it can be anything). // See https://github.com/microsoft/TypeScript/issues/45167 throw new Error(`Tried to unwrap Ok: ${toString(this.value)}`, { cause: this.value as any }); } map(mapper: (val: T) => T2): Ok { return new Ok(mapper(this.value)); } andThen(mapper: (val: T) => Result): Result { return mapper(this.value); } mapErr(_mapper: unknown): Ok { return this; } mapOr(_default_: U, mapper: (val: T) => U): U { return mapper(this.value); } mapOrElse(_default_: (_error: never) => U, mapper: (val: T) => U): U { return mapper(this.value); } or(_other: Result): Ok { return this; } orElse(_other: (error: never) => Result): Result { return this; } toOption(): Option { return Some(this.value); } toString(): string { return `Ok(${toString(this.value)})`; } toAsyncResult(): AsyncResult { return new AsyncResult(this); } } // This allows Ok to be callable - possible because of the es5 compilation target export const Ok = OkImpl as typeof OkImpl & ((val: T) => Ok); export type Ok = OkImpl; export type Result = Ok | Err; export type ResultOkType> = T extends Ok ? U : never; export type ResultErrType = T extends Err ? U : never; export type ResultOkTypes[]> = { [key in keyof T]: T[key] extends Result ? ResultOkType : never; }; export type ResultErrTypes[]> = { [key in keyof T]: T[key] extends Result ? ResultErrType : never; }; /** * A utility type that extracts the `Ok` value types from an object of `Result`s, * producing an object of the inner types. * * @example * ```typescript * type Input = { name: Result; age: Result } * type Output = ResultOkTypesRecord // { name: string; age: number } * ``` */ export type ResultOkTypesRecord>> = { [key in keyof T]: ResultOkType; }; /** * A utility type that extracts the `Err` value types from an object of `Result`s, * producing an object of the error types. * * @example * ```typescript * type Input = { name: Result; age: Result } * type Output = ResultErrTypesRecord // { name: Error; age: TypeError } * ``` */ export type ResultErrTypesRecord>> = { [key in keyof T]: ResultErrType; }; /** * Extracts the keyed first error returned when combining * an object of `Result`s. * * @example * ```typescript * type FormFields = { * name: Result; * age: Result; * }; * * type FieldError = ResultErrEntry; * // { key: 'name'; error: NameError } | { key: 'age'; error: AgeError } * * function messageFor(error: FieldError): string { * switch (error.key) { * case 'name': * return formatNameError(error.error); * case 'age': * return formatAgeError(error.error); * } * } * ``` */ export type ResultErrEntry>> = { [key in keyof T]: ResultErrType extends never ? never : { key: key; error: ResultErrType }; }[keyof T]; export namespace Result { /** * Parse a set of `Result`s, returning an array of all `Ok` values. * Short circuits with the first `Err` found, if any * * @example * ```typescript * let results: Result[] = pizzaToppingNames.map(name => getPizzaToppingByName(name)); * * let result = Result.all(results); // Result * * let toppings = result.unwrap(); // toppings is an array of Topping. Could throw GetToppingsError. * ``` */ export function all[]>( results: T, ): Result, ResultErrTypes[number]>; /** * Parse an object of `Result`s, returning an object of all `Ok` values. * By default it short-circuits with the first `Err`, returning the property * name and error. When multiple inputs are `Err`, callers must not rely on * which `Err` is returned. Passing `{}` or `{ errors: 'first' }` makes the * default short-circuit behavior explicit. Passing `{ errors: 'all' }` * collects all errors into an object where only keys that were `Err` are * present. * * @example * ```typescript * const name: Result = Ok('Alice'); * const age: Result = Ok(36); * * const parsed = Result.all({ * name, * age, * }); * // Ok({ name: 'Alice', age: 36 }) * // type: Result< * // { name: string; age: number }, * // { key: 'name'; error: NameError } | { key: 'age'; error: AgeError } * // > * * const invalidName: Result = Err(nameError); * const invalidAge: Result = Err(ageError); * * const firstError = Result.all({ * name: invalidName, * age: invalidAge, * }); * // Err({ key: 'name', error: nameError }) or * // Err({ key: 'age', error: ageError }); callers must not depend on * // which one is returned when multiple inputs are Err. * // type: Result< * // { name: string; age: number }, * // { key: 'name'; error: NameError } | { key: 'age'; error: AgeError } * // > * * const sameFirstError = Result.all({ * name: invalidName, * age: invalidAge, * }, { errors: 'first' }); * // Same behavior and type as the default short-circuit call above. * * const omittedErrors = Result.all({ * name: invalidName, * age: invalidAge, * }, {}); * // Same behavior and type as the default short-circuit call above. * * const allErrors = Result.all({ * name: invalidName, * age: invalidAge, * }, { errors: 'all' }); * // Err({ name: nameError, age: ageError }) * // type: Result< * // { name: string; age: number }, * // Partial<{ name: NameError; age: AgeError }> * // > * ``` */ export function all>>( results: T, ): Result, ResultErrEntry>; export function all>>( results: T, options: { errors?: 'first' }, ): Result, ResultErrEntry>; export function all>>( results: T, options: { errors: 'all' }, ): Result, Partial>>; // Options whose mode is not known at compile time are intentionally not // supported because the return error shape depends on that mode. export function all( results: Result[] | Record>, options?: { errors?: 'first' | 'all' }, ): Result { if (Array.isArray(results)) { const okResult = []; for (const result of results) { if (result.isOk()) { okResult.push(result.value); } else { return result as Err; } } return new Ok(okResult); } else if (options !== undefined && options.errors === 'all') { const okResult: Record = {}; const errResult: Record = {}; let hasErr = false; for (const [key, result] of Object.entries(results)) { if (result.isOk()) { okResult[key] = result.value; } else { errResult[key] = result.error; hasErr = true; } } return hasErr ? new Err(errResult) : new Ok(okResult); } else { const okResult: Record = {}; for (const [key, result] of Object.entries(results)) { if (result.isOk()) { okResult[key] = result.value; } else { return new Err({ key, error: result.error }); } } return new Ok(okResult); } } /** * Parse a set of `Result`s, short-circuits when an input value is `Ok`. * If no `Ok` is found, returns an `Err` containing the collected error values * * @example * ```typescript * let connections: Array> = [attempt1(), attempt2(), attempt3()]; * * let results = Result.any(connections); // Result * * let url = results.unwrap(); // At least one attempt gave us a successful url * ``` */ export function any[]>( results: T, ): Result[number], ResultErrTypes> { const errResult = []; // short-circuits for (const result of results) { if (result.isOk()) { return result as Ok[number]>; } else { errResult.push(result.error); } } // it must be a Err return new Err(errResult as ResultErrTypes); } /** * Wrap an operation that may throw an Error (`try-catch` style) into checked exception style * @param op The operation function * * @example * ```typescript * Result.wrap(() => JSON.parse('{"valid": "json"}')) // Ok({ valid: 'json' }), type: Result * * Result.wrap(() => JSON.parse('not json')) // Err(SyntaxError: ...), type: Result * ``` */ export function wrap(op: () => T): Result { try { return new Ok(op()); } catch (e) { return new Err(e as E); } } /** * Wrap an async operation that may throw an Error (`try-catch` style) into checked exception style * @param op The operation function * * @example * ```typescript * await Result.wrapAsync(() => fetch('/api/data').then(r => r.json())) // Ok(data) or Err(error), type: Result * ``` */ export function wrapAsync(op: () => Promise): Promise> { try { return op() .then((val) => new Ok(val)) .catch((e) => new Err(e)); } catch (e) { return Promise.resolve(new Err(e as E)); } } /** * Partitions a set of results, separating the `Ok` and `Err` values. * * @example * ```typescript * let results: Result[] = [Ok(1), Err('error1'), Ok(2), Err('error2')]; * * let [numbers, errors] = Result.partition(results); // [ [1, 2], ['error1', 'error2'] ] * ``` */ export function partition[]>(results: T): [ResultOkTypes, ResultErrTypes] { return results.reduce( ([oks, errors], v) => v.isOk() ? [[...oks, v.value] as ResultOkTypes, errors] : [oks, [...errors, v.error] as ResultErrTypes], [[], []] as [ResultOkTypes, ResultErrTypes], ); } export function isResult(val: unknown): val is Result { return val instanceof Err || val instanceof Ok; } }