onrails logoonrails

@onrails/result API

Complete API reference for @onrails/result

@onrails/result API Reference

Core

bimap ƒ

Transform both tracks at once — Ok via onOk, Err via onErr. Equivalent to mapErr(onErr)(map(onOk)(result)) but in one pass.

function bimap<T, U, E, F>(result: Result<T, E>, onOk: (value: T) => U, onErr: (error: E) => F): Result<U, F>
function bimap<T, U, E, F>(onOk: (value: T) => U, onErr: (error: E) => F): (result: Result<T, E>) => Result<U, F>

Parameters

ParameterTypeDescription
resultResult<T, E>
onOk(value: T) => U
onErr(error: E) => F

Example

bimap(parsed, (cfg) => cfg.name, (e) => ({ kind: "input", cause: e }));

err ƒ

Lifts a value into the error track.

function err<const E extends Payload[]>(error: E): Result<never, E>
function err<const E>(error: E): Result<never, E>
function err<T, E>(error: E): Result<T, E>

Parameters

ParameterTypeDescription
errorE

Example

const r = err({ kind: "parse", message: "bad json" });
// Result<never, { readonly kind: "parse"; readonly message: string }>

type AppError = { kind: "parse" } | { kind: "io" };
err<AppError>({ kind: "io" });          // Result<never, AppError> — one arg names the error
err<number, AppError>({ kind: "io" });  // Result<number, AppError> — neverthrow's T, E order

flatMap ƒ

Canonical bind (Fantasy Land chain). Chains a Result-returning step, widening the error union to E | F. Short-circuits on Err.

function flatMap<T, U, E, F>(result: Result<T, E>, fn: (value: T) => Result<U, F>): Result<U, E | F>
function flatMap<T, U, F>(fn: (value: T) => Result<U, F>): <E>(result: Result<T, E>) => Result<U, F | E>

Parameters

ParameterTypeDescription
resultResult<T, E>
fn(value: T) => Result<U, F>

Example

flatMap(parseInput(raw), (data) =>
  data.id != null ? ok(data) : err({ kind: "missing_id" as const }),
);
// Result<Data, ParseError | { kind: "missing_id" }>

flow ƒ

Variadic point-free composition — chains up to twelve unary fns left-to-right into one reusable function. The first fn may take multiple arguments; the rest are unary. Use pipe from @onrails/result when you already have a starting value; use flow to define a reusable composed function with no value yet.

function flow<A extends readonly unknown[], B>(ab: (...a: A) => B): (...a: A) => B
function flow<A extends readonly unknown[], B, C>(ab: (...a: A) => B, bc: (b: B) => C): (...a: A) => C
function flow<A extends readonly unknown[], B, C, D>(ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D): (...a: A) => D
function flow<A extends readonly unknown[], B, C, D, E>(ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E): (...a: A) => E
function flow<A extends readonly unknown[], B, C, D, E, F>(ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F): (...a: A) => F
function flow<A extends readonly unknown[], B, C, D, E, F, G>(ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G): (...a: A) => G
function flow<A extends readonly unknown[], B, C, D, E, F, G, H>(ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H): (...a: A) => H
function flow<A extends readonly unknown[], B, C, D, E, F, G, H, I>(ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I): (...a: A) => I
function flow<A extends readonly unknown[], B, C, D, E, F, G, H, I, J>(ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J): (...a: A) => J
function flow<A extends readonly unknown[], B, C, D, E, F, G, H, I, J, K>(ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K): (...a: A) => K
function flow<A extends readonly unknown[], B, C, D, E, F, G, H, I, J, K, L>(ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L): (...a: A) => L
function flow<A extends readonly unknown[], B, C, D, E, F, G, H, I, J, K, L, M>(ab: (...a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M): (...a: A) => M

Parameters

ParameterTypeDescription
ab(...a: A) => B

Example

const parseUserName = flow(
  (raw: string) => parseConfig(raw),
  map((cfg) => cfg.user),
  flatMap((u) => (u.name ? ok(u.name) : err({ kind: "missing" as const }))),
);

parseUserName(raw); // Result<string, ParseError | { kind: "missing" }>

foldSeq ƒ

Threads a state through the items, one step at a time. Each step reads the state the step before it produced. A failed step is recorded in failed and leaves the state as it was.

function foldSeq<A, S, E>(items: SeqSource<A>, init: S, fn: (state: S, item: A) => Step<S, E>): ResultAsync<FoldSeqOutput<S, A, E>, never>
function foldSeq<A, S, E>(init: S, fn: (state: S, item: A) => Step<S, E>): (items: SeqSource<A>) => ResultAsync<FoldSeqOutput<S, A, E>, never>

Parameters

ParameterTypeDescription
itemsSeqSource<A>
initS
fn(state: S, item: A) => Step<S, E>

Example

// Add each topic after the last one that was added; count the misses.
const added = foldSeq(topicIds, null as Anchor | null, (after, id) =>
  addTopic(bookId, id, after).map(() => ({ id })),
);
// ResultAsync<{ state: Anchor | null; failed: readonly { item: string; error: AddError }[] }, never>

FoldSeqOutput type

Output of foldSeq: the final state and the failed steps, in input order.

export type FoldSeqOutput<S, A, E> = {
  readonly state: S;
  readonly failed: readonly SeqFailure<A, E>[];
};

fromThrowable ƒ

Wraps a throwing sync function, returning a function that produces a Result instead of throwing. Thrown errors pass through onThrow to become a typed Err; a normal return becomes Ok. Same name and shape as neverthrow's Result.fromThrowable.

Reach for trySync instead when you want to run the call right now rather than build a reusable wrapper.

function fromThrowable<A extends readonly unknown[], T, E>(fn: (...args: A) => T, onThrow: (error: unknown) => E): (...args: A) => Result<T, E>
function fromThrowable<F extends (...args: never) => unknown, E>(fn: F, onThrow: (error: unknown) => E): (...args: Parameters<F>) => Result<ReturnType<F>, E>

Parameters

ParameterTypeDescription
fn(...args: A) => T- the throwing function to wrap
onThrow(error: unknown) => E- maps a thrown value to the Err channel

Returns

a function with fn's parameters that returns Result<ReturnType, E>

Example

type ParseError = { kind: "parse"; message: string };
const parse = fromThrowable(
  JSON.parse,
  (e): ParseError => ({ kind: "parse", message: String(e) }),
);
parse("{}");      // Ok({})
parse("nope");    // Err({ kind: "parse", … })

isErr ƒ

Type-narrowing predicate: returns true when the result is Err.

function isErr<T, E>(result: Result<T, E>): result is Err<T, E>

Parameters

ParameterTypeDescription
resultResult<T, E>

Example

if (isErr(r)) {
  metrics.inc("error", { kind: r.error.kind });
}

isOk ƒ

Type-narrowing predicate: returns true when the result is Ok.

function isOk<T, E>(result: Result<T, E>): result is Ok<T, E>

Parameters

ParameterTypeDescription
resultResult<T, E>

Example

if (isOk(r)) {
  console.log(r.value);    // narrowed to Ok branch
}

map ƒ

Transform the Ok value, passing Err through unchanged. Dual-form: call data-first or curried (for use with pipe).

function map<T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E>
function map<T, U>(fn: (value: T) => U): <E>(result: Result<T, E>) => Result<U, E>

Parameters

ParameterTypeDescription
resultResult<T, E>
fn(value: T) => U

Example

map(ok(2), (n) => n * 3);          // Ok 6 — data-first
pipe(ok("x"), map((s) => s.length));// Ok 1 — curried

mapErr ƒ

Transform the Err value, passing Ok through unchanged. Useful for unifying heterogeneous failure types into one app-level union.

function mapErr<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F>
function mapErr<E, F>(fn: (error: E) => F): <T>(result: Result<T, E>) => Result<T, F>

Parameters

ParameterTypeDescription
resultResult<T, E>
fn(error: E) => F

Example

type AppError = { kind: "http"; status: number } | { kind: "parse" };
pipe(
  fetchSync(url),                                     // Result<Body, { status: number }>
  mapErr((e): AppError => ({ kind: "http", status: e.status })),
);

match ƒ

Terminal collapse — fold both tracks into a single value. Dual-form: 3-args data-first, 2-args curried for pipe. Returns whatever the handlers return.

For files that also import match from ts-pattern, use a namespace import (import * as R from "@onrails/result" → R.match) to dissolve the collision.

function match<T, E, U>(result: Result<T, E>, onOk: (value: T) => U, onErr: (error: E) => U): U
function match<T, E, U>(onOk: (value: T) => U, onErr: (error: E) => U): (result: Result<T, E>) => U

Parameters

ParameterTypeDescription
resultResult<T, E>
onOk(value: T) => U
onErr(error: E) => U

Example

const html = match(parsed, (cfg) => render(cfg), (e) => renderError(e));

of ƒ

Fantasy Land pure — alias of ok. One lift name shared across the trio (of / Maybe.of / ResultAsync.of) for generic and FL-style code.

function of<const T extends Payload[]>(value: T): Result<T, never>
function of<const T>(value: T): Result<T, never>
function of<T, E>(value: T): Result<T, E>

Parameters

ParameterTypeDescription
valueT

Example

const r = of(42);   // Result<42, never> — identical to ok(42)

ok ƒ

Lifts a value into the success track.

function ok<const T extends Payload[]>(value: T): Result<T, never>
function ok<const T>(value: T): Result<T, never>
function ok<T, E>(value: T): Result<T, E>

Parameters

ParameterTypeDescription
valueT

Example

const r = ok(42);                          // Result<42, never> — literal locked
const typed: Result<number, "parse"> = ok(1);
const lift = <T, E>(v: T): Result<T, E> => ok(v);         // generic T passes through

pipe ƒ

Variadic value-first pipe — threads value through up to twelve unary fns, left-to-right. Use pipe when you already have a starting value; use flow to define a reusable composed function with no value yet.

function pipe<A>(value: A): A
function pipe<A, B>(value: A, ab: (a: A) => B): B
function pipe<A, B, C>(value: A, ab: (a: A) => B, bc: (b: B) => C): C
function pipe<A, B, C, D>(value: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D): D
function pipe<A, B, C, D, E>(value: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E): E
function pipe<A, B, C, D, E, F>(value: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F): F
function pipe<A, B, C, D, E, F, G>(value: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G): G
function pipe<A, B, C, D, E, F, G, H>(value: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H): H
function pipe<A, B, C, D, E, F, G, H, I>(value: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I): I
function pipe<A, B, C, D, E, F, G, H, I, J>(value: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J): J
function pipe<A, B, C, D, E, F, G, H, I, J, K>(value: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K): K
function pipe<A, B, C, D, E, F, G, H, I, J, K, L>(value: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L): L
function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M>(value: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E, ef: (e: E) => F, fg: (f: F) => G, gh: (g: G) => H, hi: (h: H) => I, ij: (i: I) => J, jk: (j: J) => K, kl: (k: K) => L, lm: (l: L) => M): M

Parameters

ParameterTypeDescription
valueA

Example

pipe(
  parseConfig(raw),
  map((cfg) => cfg.user),
  flatMap((u) => (u.name ? ok(u.name) : err({ kind: "missing" as const }))),
);

recover ƒ

Error-track bind — runs fn only when the result is Err, allowing a failed workflow to recover to Ok or remap the failure. Mirror of flatMap on the error channel.

function recover<T, E, F>(result: Result<T, E>, fn: (error: E) => Result<T, F>): Result<T, F>
function recover<T, E, F>(fn: (error: E) => Result<T, F>): (result: Result<T, E>) => Result<T, F>

Parameters

ParameterTypeDescription
resultResult<T, E>
fn(error: E) => Result<T, F>

Example

recover(networkResult, (e) =>
  e.kind === "rate_limit" ? ok(cachedBody) : err(e),
);

ResultData type

Plain-data shape of a Result: what JSON.parse, structuredClone and postMessage hand back. It has no methods; lift it with Result.from.

export type ResultData<T, E> =
  | { readonly _tag: "Ok"; readonly value: T }
  | { readonly _tag: "Err"; readonly error: E };

SeqFailure type

One failed step: the item it ran on and the Err it returned.

export type SeqFailure<A, E> = { readonly item: A; readonly error: E };

SeqSource type

A sync or async source of items.

export type SeqSource<A> = Iterable<A> | AsyncIterable<A>;

show ƒ

Debug printer — renders a result as Ok(…) / Err(…) for logs. Payloads print as JSON (values are plain data by design); non-JSON payloads fall back to String(...).

function show<T, E>(result: Result<T, E>): string

Parameters

ParameterTypeDescription
resultResult<T, E>

Example

show(ok(1));               // 'Ok(1)'
show(err({ kind: "e" })); // 'Err({"kind":"e"})'

tap ƒ

Observe the Ok value for side effects (logging, metrics) without changing the carried value. Passes Err through untouched.

function tap<T, E>(result: Result<T, E>, fn: (value: T) => void): Result<T, E>
function tap<T>(fn: (value: T) => void): <E>(result: Result<T, E>) => Result<T, E>

Parameters

ParameterTypeDescription
resultResult<T, E>
fn(value: T) => void

Example

pipe(
  parseConfig(raw),
  tap((cfg) => log.info({ msg: "parsed", name: cfg.name })),
  flatMap(validate),
);

tapErr ƒ

Observe the Err value for side effects (logging, metrics) without changing the carried error. Passes Ok through untouched.

function tapErr<T, E>(result: Result<T, E>, fn: (error: E) => void): Result<T, E>
function tapErr<E>(fn: (error: E) => void): <T>(result: Result<T, E>) => Result<T, E>

Parameters

ParameterTypeDescription
resultResult<T, E>
fn(error: E) => void

Example

pipe(
  loadUser(id),
  tapErr((e) => metrics.inc("user.load.fail", { kind: e.kind })),
);

traverseSeq ƒ

Runs fn on each item, one at a time, and collects the results. A step starts only after the one before it has settled. A failed step is recorded in failed and the traversal goes on; the carrier itself never fails.

function traverseSeq<A, T, E>(items: SeqSource<A>, fn: (item: A) => Step<T, E>): ResultAsync<TraverseSeqOutput<T, A, E>, never>
function traverseSeq<A, T, E>(fn: (item: A) => Step<T, E>): (items: SeqSource<A>) => ResultAsync<TraverseSeqOutput<T, A, E>, never>

Parameters

ParameterTypeDescription
itemsSeqSource<A>
fn(item: A) => Step<T, E>

Example

// Move each object in turn (two at once collide); report the refused ids.
const moved = traverseSeq(ids, (id) => changeState(id));
// ResultAsync<{ ok: readonly State[]; failed: readonly { item: number; error: StateError }[] }, never>

TraverseSeqOutput type

Output of traverseSeq: Ok values and failed steps, both in input order.

export type TraverseSeqOutput<T, A, E> = {
  readonly ok: readonly T[];
  readonly failed: readonly SeqFailure<A, E>[];
};

trySync ƒ

Runs fn now, catching a throw into the Err track — the sync mirror of tryAsync. Without onThrow the thrown value is normalized to an Error; pass a mapper for a typed error.

To lift a throwing function once and call it many times, use fromThrowable.

function trySync<T>(fn: () => T): Result<T, Error>
function trySync<T, E>(fn: () => T, onThrow: (error: unknown) => E): Result<T, E>

Parameters

ParameterTypeDescription
fn() => T- the throwing thunk to run

Example

trySync(() => JSON.parse(raw));                    // Result<unknown, Error>
trySync(() => Schema.parse(input), (e): SchemaError => ({
  kind: "schema",
  cause: e,
}));

unwrap ƒ

Alias of unwrapOk for syntax cohesion with @onrails/maybe.

function unwrap<T, E>(result: Result<T, E>): T

Parameters

ParameterTypeDescription
resultResult<T, E>

unwrapErr ƒ

Test/assert helper — returns the Err value, or throws a TypeError when called on an Ok. Mirror of unwrapOk on the error track and part of the same assertion tier (RFC 0001 §4): intended for *.spec.ts / *.test.ts. Prefer match / unwrapOr in business logic; the lint plugins flag unwrapErr outside test files.

function unwrapErr<T, E>(result: Result<T, E>): E

Parameters

ParameterTypeDescription
resultResult<T, E>

Returns

the unwrapped Err value

Example

// in a *.spec.ts
expect(unwrapErr(err("x"))).toBe("x");
expect(() => unwrapErr(ok(5))).toThrow(TypeError);

unwrapOk ƒ

Test/assert helper — returns the Ok value, or throws the original Err value when called on an Err. This is the assertion tier (RFC 0001 §4): intended for *.spec.ts / *.test.ts, where throwing fails the test loudly. In business logic prefer match or unwrapOr; the lint plugins flag unwrapOk outside test files.

function unwrapOk<T, E>(result: Result<T, E>): T

Parameters

ParameterTypeDescription
resultResult<T, E>

Returns

the unwrapped Ok value

Example

// in a *.spec.ts
expect(unwrapOk(ok(5))).toBe(5);
expect(() => unwrapOk(err(error))).toThrow(error);

unwrapOr ƒ

Returns the Ok value, or defaultValue when the result is Err. The fallback may be a different type from T — the return widens to T | U, matching ResultAsync.unwrapOr and the compat shim.

function unwrapOr<T, E, U>(result: Result<T, E>, defaultValue: U): T | U
function unwrapOr<U>(defaultValue: U): <T, E>(result: Result<T, E>) => U | T

Parameters

ParameterTypeDescription
resultResult<T, E>
defaultValueU

Example

unwrapOr(parsedSetting, "default-value");  // string
unwrapOr(parsedPort, null);                // number | null

validateAll ƒ

Accumulate independent validation failures. Returns Ok<T[]> only when every input is Ok. Without a combiner, failures are collected into a readonly array; with combineErrors they are folded into a single E.

Unlike combine, this does not short-circuit on first failure — use for independent checks where you want to report all problems at once.

function validateAll<T, E>(results: Iterable<Result<T, E>>): Result<T[], readonly E[]>
function validateAll<T, E>(results: Iterable<Result<T, E>>, combineErrors: (left: E, right: E) => E): Result<T[], E>

Parameters

ParameterTypeDescription
resultsIterable<Result<T, E>>

Example

const checks: Result<string, string[]>[] = [ok("Ada"), err(["age required"])];

validateAll(checks);
// Result<string[], readonly string[][]>

validateAll(checks, (left, right) => [...left, ...right]);
// Result<string[], string[]>

validateTuple ƒ

Tuple-preserving variant of validateAll. Heterogeneous input tuple → preserved Ok tuple shape. Without a combiner, the error union is collected into a readonly array; with combineErrors, all inputs must share the error type E and failures fold into a single E.

Like combineTuple, the element check lives in the return type, so inline literals keep their precise error types without as const.

function validateTuple<const R extends readonly unknown[]>(results: R, ..._guard: TupleGuard<R>): R[number] extends AnyResult ? Result<OkTuple<R>, readonly InferErr<R[number]>[]> : never
function validateTuple<const R extends readonly unknown[], E = InferErr<R[number]>>(results: R, combineErrors: (left: E, right: E) => E, ..._guard: TupleGuard<R>): R[number] extends AnyResult ? Result<...> : never

Parameters

ParameterTypeDescription
resultsR
_guardTupleGuard<R>

Example

const name: Result<string, string[]> = ok("Ada");
const age: Result<number, string[]> = ok(36);

validateTuple([name, age]);
// Result<readonly [string, number], readonly string[][]>

validateTuple([name, age], (l, r) => [...l, ...r]);
// Result<readonly [string, number], string[]>

Async

errAsync ƒ

Lifts a value into an Err async result.

function errAsync<const E extends Payload[]>(error: E): ResultAsync<never, E>
function errAsync<const E>(error: E): ResultAsync<never, E>
function errAsync<T, E>(error: E): ResultAsync<T, E>

Parameters

ParameterTypeDescription
errorE

Example

const r = errAsync({ kind: "not_found" as const });

fromPromise ƒ

Wraps a PromiseLike<T> into a ResultAsync. Reject reasons go through onReject to become typed Errs; success becomes Ok<T>.

function fromPromise<T, E>(promise: PromiseLike<T>, onReject: (error: unknown) => E): ResultAsync<T, E>

Parameters

ParameterTypeDescription
promisePromiseLike<T>
onReject(error: unknown) => E

Example

const body = fromPromise(
  fetch(url).then((r) => r.text()),
  (e): NetworkError => ({ kind: "network", cause: String(e) }),
);

fromSafePromise ƒ

Wraps a PromiseLike<T> that never rejects into ResultAsync. Skips the onReject mapper. Use only when the promise is provably safe.

function fromSafePromise<T, E = never>(promise: PromiseLike<T>): ResultAsync<T, E>

Parameters

ParameterTypeDescription
promisePromiseLike<T>

okAsync ƒ

Lifts a value into an Ok async result.

function okAsync<const T extends Payload[]>(value: T): ResultAsync<T, never>
function okAsync<const T>(value: T): ResultAsync<T, never>
function okAsync<T, E>(value: T): ResultAsync<T, E>

Parameters

ParameterTypeDescription
valueT

Example

const r = okAsync(42);   // ResultAsync<42, never> — literal locked

ResultAsync class

Async railway carrier. Wraps a deferred Promise<Result<T, E>> and exposes the same dual-track transforms as the sync Result — map, mapErr, bimap, flatMap, recover, tap, match. The public API never surfaces Promise<Result<…>> directly: await the instance (it is thenable) or call resolve / match to settle it.

Construct via the static factories (ok, err, fromPromise, defer, …) rather than new — the constructor is protected.

class ResultAsync

Example

const user = ResultAsync.fromPromise(api.getUser(id), toAppError)
  .map((u) => u.profile)
  .recover(() => ResultAsync.ok(guestProfile));

const r = await user;          // Result<Profile, AppError>

new ResultAsync constructor

constructor<T, E>(run: PromiseFactory<T, E>): ResultAsync<T, E>

ResultAsync.fromResult ƒ

Lifts an already-settled sync Result into a ResultAsync.

static fromResult<T, E>(result: Result<T, E>): ResultAsync<T, E>

Parameters

ParameterTypeDescription
resultResult<T, E>

Example

const ra = ResultAsync.fromResult(ok(42));   // ResultAsync<number, never>

ResultAsync.fromPromise ƒ

Wraps a PromiseLike<T> that may reject. Rejections pass through onReject to become a typed Err; resolution becomes Ok<T>.

static fromPromise<T, E>(promise: PromiseLike<T>, onReject: (error: unknown) => E): ResultAsync<T, E>

Parameters

ParameterTypeDescription
promisePromiseLike<T>- the promise to wrap
onReject(error: unknown) => E- maps a rejection reason to the Err channel

Example

const body = ResultAsync.fromPromise(
  fetch(url).then((r) => r.text()),
  (e): NetError => ({ kind: "net", cause: String(e) }),
);

ResultAsync.fromSafePromise ƒ

Wraps a PromiseLike<T> that is guaranteed not to reject, skipping the onReject mapper. Use only when rejection is provably impossible.

static fromSafePromise<T, E = never>(promise: PromiseLike<T>): ResultAsync<T, E>

Parameters

ParameterTypeDescription
promisePromiseLike<T>

Example

const now = ResultAsync.fromSafePromise(Promise.resolve(Date.now()));

ResultAsync.defer ƒ

Defers work until resolve. Unlike fromPromise, the factory does not run until the ResultAsync is resolved (e.g. by combineTuple / combineTupleParallel). The factory runs at most once — resolve memoizes.

static defer<T, E>(fn: () => Promise<Result<T, E>>): ResultAsync<T, E>

Parameters

ParameterTypeDescription
fn() => Promise<Result<T, E>>

Example

const insert = ResultAsync.defer(() => db.orders.insert(row));
// nothing has run yet
const r = await insert;   // factory runs exactly once here

ResultAsync.ok ƒ

Lifts a value into an Ok async result.

static ok<const T extends Payload[]>(value: T): ResultAsync<T, never>
static ok<const T>(value: T): ResultAsync<T, never>
static ok<T, E>(value: T): ResultAsync<T, E>

Parameters

ParameterTypeDescription
valueT

Example

const r = ResultAsync.ok(42);   // ResultAsync<number, never>

ResultAsync.of ƒ

Fantasy Land pure — alias of ResultAsync.ok. One lift name shared across the trio (of / Maybe.of / ResultAsync.of).

static of<const T extends Payload[]>(value: T): ResultAsync<T, never>
static of<const T>(value: T): ResultAsync<T, never>
static of<T, E>(value: T): ResultAsync<T, E>

Parameters

ParameterTypeDescription
valueT

ResultAsync.err ƒ

Lifts an error into an Err async result.

static err<const E extends Payload[]>(error: E): ResultAsync<never, E>
static err<const E>(error: E): ResultAsync<never, E>
static err<T, E>(error: E): ResultAsync<T, E>

Parameters

ParameterTypeDescription
errorE

Example

const r = ResultAsync.err({ kind: "not_found" as const });

ResultAsync.fromResultPromise ƒ

Lifts an existing Promise<Result<T, E>> (e.g. from interop code) into a ResultAsync. A thrown defect is routed through onDefect, defaulting to UnexpectedError. The Ok value passes through verbatim — even when it happens to be Result-shaped.

static fromResultPromise<T, E>(promise: Promise<Result<T, E>>, onDefect?: ((error: unknown) => E | UnexpectedError) | undefined): ResultAsync<T, E | UnexpectedError>

Parameters

ParameterTypeDescription
promisePromise<Result<T, E>>- a promise that already yields a Result
onDefect((error: unknown) => E | UnexpectedError) | undefined- maps an unexpected throw to the Err channel

ResultAsync.combine ƒ

Combines a homogeneous array of async results into one. Resolves sequentially in input order, short-circuiting on the first Err. For heterogeneous tuples that preserve per-index types, use combineTuple; for wall-clock overlap, combineTupleParallel.

static combine<T, E>(results: readonly ResultAsync<T, E>[]): ResultAsync<T[], E>

Parameters

ParameterTypeDescription
resultsreadonly ResultAsync<T, E>[]

Example

const all = ResultAsync.combine([loadA(), loadB(), loadC()]);
// ResultAsync<Item[], LoadError>

ResultAsync.combineTuple ƒ

Heterogeneous async tuple combine — resolves branches sequentially (left-to-right), returning the first Err in input order. Preserves each branch's Ok type by position, so the result destructures type-safely. This is the canonical sequential async combine (replaces the former sequenceTupleAsync).

static combineTuple<const R extends readonly unknown[]>(results: R, ..._guard: AsyncTupleGuard<R>): CombineTupleAsync<R>

Parameters

ParameterTypeDescription
resultsR
_guardAsyncTupleGuard<R>

Example

const combined = ResultAsync.combineTuple([loadCfg(), loadCatalog()]);
// ResultAsync<readonly [Cfg, Catalog], CfgError | CatalogError>
const r = await combined;
if (isOk(r)) {
  const [cfg, catalog] = r.value;  // typed per position
}

ResultAsync.combineTupleParallel ƒ

Like combineTuple, but starts every branch before awaiting (wall-clock parallel for independent IO). On failure, returns the first Err in input order.

static combineTupleParallel<const R extends readonly unknown[]>(results: R, ..._guard: AsyncTupleGuard<R>): CombineTupleAsync<R>

Parameters

ParameterTypeDescription
resultsR
_guardAsyncTupleGuard<R>

Example

// independent IO — overlap them
const combined = ResultAsync.combineTupleParallel([
  loadProfile(id),
  loadMetrics(id),
]);

ResultAsync.prototype.map ƒ

Transforms the Ok value, passing Err through unchanged.

map<U>(fn: (value: T) => U): ResultAsync<U, E>

Parameters

ParameterTypeDescription
fn(value: T) => U

Example

ResultAsync.ok(2).map((n) => n * 3);   // ResultAsync<number> → Ok 6

ResultAsync.prototype.mapErr ƒ

Transforms the Err value, passing Ok through unchanged — useful for unifying heterogeneous failures into one app-level union.

mapErr<F>(fn: (error: E) => F): ResultAsync<T, F>

Parameters

ParameterTypeDescription
fn(error: E) => F

Example

load(id).mapErr((e): AppError => ({ kind: "load", cause: e })); // ResultAsync<T, AppError>

ResultAsync.prototype.bimap ƒ

Transforms both tracks in one step — the async mirror of the sync bimap. Exactly one of onOk / onErr runs.

bimap<U, F>(onOk: (value: T) => U, onErr: (error: E) => F): ResultAsync<U, F>

Parameters

ParameterTypeDescription
onOk(value: T) => U
onErr(error: E) => F

Example

load(id).bimap(toDto, (e): AppError => ({ kind: "load", cause: e }));

ResultAsync.prototype.flatMap ƒ

Canonical bind — chains a step that itself returns a ResultAsync or sync Result, short-circuiting on Err. Error types accumulate (E | F).

flatMap<U, F = E>(fn: (value: T) => ResultAsync<U, F> | Result<U, F>): ResultAsync<U, E | F>

Parameters

ParameterTypeDescription
fn(value: T) => ResultAsync<U, F> | Result<U, F>

Example

authenticate(req)
  .flatMap((user) => loadProfile(user.id))   // ResultAsync
  .flatMap((p) => validate(p));              // sync Result also accepted

ResultAsync.prototype.andThen ƒ

neverthrow-compat alias of flatMap. Kept as the documented compat tier; prefer flatMap in new code.

andThen<U, F = E>(fn: (value: T) => ResultAsync<U, F> | Result<U, F>): ResultAsync<U, E | F>

Parameters

ParameterTypeDescription
fn(value: T) => ResultAsync<U, F> | Result<U, F>

Example

authenticate(req).andThen((user) => loadProfile(user.id));

ResultAsync.prototype.recover ƒ

Error-channel bind — runs fn only on Err, swapping in a recovery ResultAsync or sync Result. Ok passes through. The mirror of flatMap on the error track.

recover<F>(fn: (error: E) => ResultAsync<T, F> | Result<T, F>): ResultAsync<T, F>

Parameters

ParameterTypeDescription
fn(error: E) => ResultAsync<T, F> | Result<T, F>

Example

loadFromCache(id).recover(() => loadFromOrigin(id)); // ResultAsync<T, F>

ResultAsync.prototype.orElse ƒ

neverthrow-compat alias of recover. Kept as the documented compat tier; prefer recover in new code.

orElse<F>(fn: (error: E) => ResultAsync<T, F> | Result<T, F>): ResultAsync<T, F>

Parameters

ParameterTypeDescription
fn(error: E) => ResultAsync<T, F> | Result<T, F>

Example

loadFromCache(id).orElse(() => loadFromOrigin(id));

ResultAsync.prototype.tap ƒ

Runs a side effect on the Ok value and passes the result through unchanged; a no-op on Err. Mirrors tapErr.

tap(fn: (value: T) => void): ResultAsync<T, E>

Parameters

ParameterTypeDescription
fn(value: T) => void

Example

saveUser(u).tap((saved) => analytics.track("user_saved", saved.id));

ResultAsync.prototype.tapErr ƒ

Runs a side effect on the Err value and passes the result through unchanged; a no-op on Ok. The error-track mirror of tap.

tapErr(fn: (error: E) => void): ResultAsync<T, E>

Parameters

ParameterTypeDescription
fn(error: E) => void

Example

saveUser(u).tapErr((e) => logger.warn("save failed", e));

ResultAsync.prototype.unwrapOr ƒ

Settles to the Ok value, or defaultValue if Err. Terminal — returns a plain Promise, not a ResultAsync.

unwrapOr<U>(defaultValue: U): Promise<T | U>

Parameters

ParameterTypeDescription
defaultValueU

Example

const profile = await loadProfile(id).unwrapOr(guestProfile);

ResultAsync.prototype.match ƒ

Terminal collapse — folds both tracks into a single awaited value. Returns a plain Promise, settling the carrier exactly once.

match<U1, U2 = U1>(onOk: (value: T) => U1, onErr: (error: E) => U2): Promise<U1 | U2>

Parameters

ParameterTypeDescription
onOk(value: T) => U1- handles the Ok value
onErr(error: E) => U2- handles the Err value

Example

const status = await save(row).match(
  () => 200,
  (e) => (e.kind === "conflict" ? 409 : 500),
);

ResultAsync.prototype.resolve ƒ

Settles the carrier to a bare sync Result, memoizing so the underlying factory runs at most once. Prefer await ra (the thenable) or match in app code; use resolve when you need the tagged union back.

resolve(): Promise<Result<T, E>>

Example

const r = await load(id).resolve();   // Result<Data, LoadError>
if (isOk(r)) use(r.value);

ResultAsync.prototype.then ƒ

Thenable shim — await ra resolves to a bare tagged-union Result<T, E>. Narrow with isOk(r) / isErr(r) to read .value / .error.

then<R1 = Result<T, E>, R2 = never>(onfulfilled?: ((value: Result<T, E>) => R1 | PromiseLike<R1>) | null | undefined, onrejected?: ((reason: unknown) => R2 | PromiseLike<...>) | null | undefined): Promise<...>

Parameters

ParameterTypeDescription
onfulfilled((value: Result<T, E>) => R1 | PromiseLike<R1>) | null | undefined
onrejected((reason: unknown) => R2 | PromiseLike<R2>) | null | undefined

tryAsync ƒ

Convenience wrapper over fromPromise with default Error normalization. Call without onReject to get ResultAsync<T, Error>, or pass a custom mapper for a typed error.

Pass a function that returns the promise when the call can throw before the promise exists. tryAsync calls it at once. A sync throw and a rejection both go through onReject.

function tryAsync<T>(source: PromiseLike<T> | (() => PromiseLike<T>)): ResultAsync<T, Error>
function tryAsync<T, E>(source: PromiseLike<T> | (() => PromiseLike<T>), onReject: (error: unknown) => E): ResultAsync<T, E>

Parameters

ParameterTypeDescription
sourcePromiseLike<T> | (() => PromiseLike<T>)

Example

// Default: rejection → Err(Error)
const a = tryAsync(db.users.insert(row));

// Custom: typed error
const b = tryAsync(db.users.insert(row), (e): DbError => ({
  kind: "db",
  cause: e,
}));

// Function form: a sync throw (bad argument) also becomes Err
const c = tryAsync(() => crypto.subtle.decrypt({ name: "AES-GCM", iv: nonce }, key, data));

Collections

combine ƒ

Combines a homogeneous iterable of results into a single result holding an array of the Ok values, in input order. Short-circuits on the first Err (first failure wins) and stops pulling from the source there. For heterogeneous tuples that preserve per-index types, use combineTuple.

function combine<T, E>(results: Iterable<Result<T, E>>): Result<T[], E>

Parameters

ParameterTypeDescription
resultsIterable<Result<T, E>>

Example

combine([ok(1), ok(2)]);        // Ok([1, 2])
combine([ok(1), err("e")]);     // Err("e")

combineTuple ƒ

Heterogeneous tuple combine — like combine but preserves each branch's Ok type by position, so the result destructures type-safely. Short-circuits on the first Err in input order (neverthrow-style).

function combineTuple<const R extends readonly unknown[]>(results: R, ..._guard: TupleGuard<R>): CombineTuple<R>

Parameters

ParameterTypeDescription
resultsR
_guardTupleGuard<R>

Example

const r = combineTuple([ok(1), ok("x")]);
// Result<readonly [number, string], never> — no `as const` needed
if (isOk(r)) {
  const [n, s] = r.value;   // typed per position
}

Interop

asyncAfter ƒ

Bind a sync Result into an async step without widening defects. Dual-form: data-first for one-shots, data-last (curried) for pipe/flow.

function asyncAfter<T, U, E, F>(result: Result<T, E>, fn: (value: T) => ResultAsync<U, F>): ResultAsync<U, E | F>
function asyncAfter<T, U, F>(fn: (value: T) => ResultAsync<U, F>): <E>(result: Result<T, E>) => ResultAsync<U, F | E>

Parameters

ParameterTypeDescription
resultResult<T, E>
fn(value: T) => ResultAsync<U, F>

Example

asyncAfter(result, (u) => tryAsync(db.insert(u), toErr)); // data-first
asyncAfter((u) => tryAsync(db.insert(u), toErr));         // data-last

fromAsync ƒ

Lifts a (...args) => Promise<Result<T, E>> function (typical of interop or boundary code) into one returning (...args) => ResultAsync<T, E>. Expected Errs pass through; an unexpected promise rejection (a defect) is routed via onDefect, defaulting to UnexpectedError and widening the error union.

function fromAsync<A extends readonly unknown[], R extends AnyResult>(fn: (...args: A) => Promise<R>, onDefect?: ((error: unknown) => UnexpectedError | InferErr<R>) | undefined): (...args: A) => ResultAsync<...>

Parameters

ParameterTypeDescription
fn(...args: A) => Promise<R>- a function returning a promise that already yields a Result
onDefect((error: unknown) => UnexpectedError | InferErr<R>) | undefined- maps an unexpected rejection to the Err channel

Example

const loadUser = fromAsync(
  (id: string): Promise<Result<User, NotFound>> => api.getUser(id),
);
const ra = loadUser("u1");   // ResultAsync<User, NotFound | UnexpectedError>

fromResult ƒ

Lifts an already-settled sync Result into a ResultAsync, so it can be chained alongside async steps in a railway.

function fromResult<T, E>(result: Result<T, E>): ResultAsync<T, E>

Parameters

ParameterTypeDescription
resultResult<T, E>

Example

const ra = fromResult(ok(1));            // ResultAsync<number, never>
await fromResult(err(error)).resolve();  // Err(error)

Generators

$ ƒ

Terse alias of yieldResult (mirrors Rust's ?), for compact tryGen blocks.

function $<T, E>(result: Result<T, E>): T

Parameters

ParameterTypeDescription
resultResult<T, E>

Example

const out = tryGen(() => {
  const a = $(parseA());
  const b = $(parseB());
  return ok(a + b);
});

tryGen ƒ

Run a block that uses yieldResult; returns the final Result or the first Err.

function tryGen<T, E>(fn: () => Result<T, E>): Result<T, E>

Parameters

ParameterTypeDescription
fn() => Result<T, E>

Example

const out = tryGen(() => {
  const a = $(parseA());
  const b = $(parseB());
  return ok(a + b);
});

yieldResult ƒ

Unwraps a Result inside a tryGen block — the sync analogue of Rust's ? operator. On Ok it returns the value; on Err it short-circuits the enclosing tryGen, which returns that Err. Only valid inside tryGen; prefer flatMap / pipe for long pipelines.

function yieldResult<T, E>(result: Result<T, E>): T

Parameters

ParameterTypeDescription
resultResult<T, E>

Returns

the unwrapped Ok value

Example

const out = tryGen(() => {
  const a = yieldResult(parseA());   // unwrap or short-circuit
  const b = yieldResult(parseB());
  return ok(a + b);
});

Types

Err type

The failure branch of a Result — { _tag: "Err"; error: E }.

export type Err<T, E> = Extract<Result<T, E>, { _tag: "Err" }>;

InferErr type

Extracts the Err error type from a Result or ResultAsync, resolving to never for any other type. Mirror of InferOk.

export type InferErr<R> = R extends { _tag: "Err"; readonly error: infer E }
  ? E
  : R extends ResultAsync<unknown, infer E>
    ? E
    : never;

Example

type E = InferErr<Result<number, string>>;        // string
type F = InferErr<ResultAsync<User, AppError>>;    // AppError

InferOk type

Extracts the Ok value type from a Result or ResultAsync, resolving to never for any other type.

export type InferOk<R> = R extends { _tag: "Ok"; readonly value: infer T }
  ? T
  : R extends ResultAsync<infer T, unknown>
    ? T
    : never;

Example

type T = InferOk<Result<number, string>>;        // number
type U = InferOk<ResultAsync<User, AppError>>;    // User

Ok type

The success branch of a Result — { _tag: "Ok"; value: T }. The E parameter keeps the type assignable to Result<T, E>.

export type Ok<T, E = never> = Extract<Result<T, E>, { _tag: "Ok" }>;

Result type

The core railway type: a tagged union carrying either a success value (Ok<T>) or a failure value (Err<E>), discriminated on _tag. Carriers are plain data (_tag plus value / error as own enumerable properties) with ResultMethods on a shared non-enumerable prototype, so JSON.stringify output is unchanged. Narrow on _tag to read .value / .error.

Build carriers with ok / err; a hand-written { _tag: "Ok", value } literal has no methods and is not a Result. Data that crossed a serialization boundary is lifted back with Result.from. Value-side companion of the Result type.

from lifts plain data back into a live Result. Use it at every deserialization sink (JSON.parse, structuredClone, postMessage, IndexedDB, Redux rehydration), where the prototype and its methods are lost while the type still claims them. It trusts the shape; validate untrusted input first. An unknown _tag is a defect and throws a TypeError rather than becoming a silent Err(undefined).

export type Result<T, E> = ResultData<T, E> & ResultMethods<T, E>;

const Result: { readonly from: <T, E>(data: ResultData<T, E>) => Result<T, E>; }

Example

function parse(raw: string): Result<number, "nan"> {
  const n = Number(raw);
  return Number.isNaN(n) ? err("nan") : ok(n);
}
parse("1").map((n) => n + 1);
const wire = JSON.parse(JSON.stringify(ok(1)));   // plain data, no methods
const live = Result.from<number, string>(wire);   // Result<number, string>
live.map((n) => n + 1);

UnexpectedError class

Error subclass representing an unexpected defect — a thrown exception or promise rejection that was not part of the modelled Err union. Used as the default mapping when fromAsync is called without an onDefect handler; the original cause is preserved on .cause.

class UnexpectedError

Example

const defect = new UnexpectedError("Unexpected async defect", caught);
defect.cause; // the original thrown value

new UnexpectedError constructor

constructor(message: string, cause?: unknown): UnexpectedError

UnexpectedError.isError ƒ

Indicates whether the argument provided is a built-in Error instance or not.

static isError(error: unknown): error is Error

Parameters

ParameterTypeDescription
errorunknown

UnexpectedError.prototype.cause ƒ

cause: unknown

UnexpectedError.prototype.name ƒ

name: string

UnexpectedError.prototype.message ƒ

message: string

UnexpectedError.prototype.stack ƒ

stack: string | undefined

On this page

@onrails/result API ReferenceCorebimap ƒParametersExampleerr ƒParametersExampleflatMap ƒParametersExampleflow ƒParametersExamplefoldSeq ƒParametersExampleFoldSeqOutput typefromThrowable ƒParametersReturnsExampleisErr ƒParametersExampleisOk ƒParametersExamplemap ƒParametersExamplemapErr ƒParametersExamplematch ƒParametersExampleof ƒParametersExampleok ƒParametersExamplepipe ƒParametersExamplerecover ƒParametersExampleResultData typeSeqFailure typeSeqSource typeshow ƒParametersExampletap ƒParametersExampletapErr ƒParametersExampletraverseSeq ƒParametersExampleTraverseSeqOutput typetrySync ƒParametersExampleunwrap ƒParametersunwrapErr ƒParametersReturnsExampleunwrapOk ƒParametersReturnsExampleunwrapOr ƒParametersExamplevalidateAll ƒParametersExamplevalidateTuple ƒParametersExampleAsyncerrAsync ƒParametersExamplefromPromise ƒParametersExamplefromSafePromise ƒParametersokAsync ƒParametersExampleResultAsync classExamplenew ResultAsync constructorResultAsync.fromResult ƒParametersExampleResultAsync.fromPromise ƒParametersExampleResultAsync.fromSafePromise ƒParametersExampleResultAsync.defer ƒParametersExampleResultAsync.ok ƒParametersExampleResultAsync.of ƒParametersResultAsync.err ƒParametersExampleResultAsync.fromResultPromise ƒParametersResultAsync.combine ƒParametersExampleResultAsync.combineTuple ƒParametersExampleResultAsync.combineTupleParallel ƒParametersExampleResultAsync.prototype.map ƒParametersExampleResultAsync.prototype.mapErr ƒParametersExampleResultAsync.prototype.bimap ƒParametersExampleResultAsync.prototype.flatMap ƒParametersExampleResultAsync.prototype.andThen ƒParametersExampleResultAsync.prototype.recover ƒParametersExampleResultAsync.prototype.orElse ƒParametersExampleResultAsync.prototype.tap ƒParametersExampleResultAsync.prototype.tapErr ƒParametersExampleResultAsync.prototype.unwrapOr ƒParametersExampleResultAsync.prototype.match ƒParametersExampleResultAsync.prototype.resolve ƒExampleResultAsync.prototype.then ƒParameterstryAsync ƒParametersExampleCollectionscombine ƒParametersExamplecombineTuple ƒParametersExampleInteropasyncAfter ƒParametersExamplefromAsync ƒParametersExamplefromResult ƒParametersExampleGenerators$ ƒParametersExampletryGen ƒParametersExampleyieldResult ƒParametersReturnsExampleTypesErr typeInferErr typeExampleInferOk typeExampleOk typeResult typeExampleUnexpectedError classExamplenew UnexpectedError constructorUnexpectedError.isError ƒParametersUnexpectedError.prototype.cause ƒUnexpectedError.prototype.name ƒUnexpectedError.prototype.message ƒUnexpectedError.prototype.stack ƒ