Skip to content

API Reference

github-actions[bot] edited this page May 13, 2026 · 18 revisions

ripthrow


ripthrow: A tiny, type-safe Result type for TypeScript. Inspired by Rust's Result and the proposed Error Handling Operator (?=).

This library provides a structured way to handle success and failure without relying on exceptions, promoting safer and more predictable code.

Builder

AsyncResultBuilder

Defined in: result-builder-async.ts:37

A fluent async wrapper around the Result type that enables method chaining on operations that return Promise<Result<T, E>>.

Start with buildAsync or AsyncResultBuilder.ok / .err / .safeAsync, then chain .map(), .andThen(), .context(), and finish with .unwrap(), .unwrapOr(), or .match().

Callbacks in .andThen() and .orElse() accept both sync Result and async Promise<Result> — you can await freely inside them.

Type Parameters

Type Parameter Description
T The success type.
E The error type.

Properties

andThen
andThen: <R>(fn) => AsyncResultBuilder<R, E>;

Defined in: result-builder-async.ts:43

Type Parameters
Type Parameter
R
Parameters
Parameter Type
fn (value) => | Result<R, E> | AsyncResult<R, E>
Returns

AsyncResultBuilder<R, E>

context
context: <C>(message, help?, meta?) => AsyncResultBuilder<T, Report<C>>;

Defined in: result-builder-async.ts:48

Type Parameters
Type Parameter
C extends Record<string, unknown>
Parameters
Parameter Type
message string
help? string
meta? C
Returns

AsyncResultBuilder<T, Report<C>>

Deprecated

Use AsyncResultBuilder.note instead.

isErr
readonly isErr: Promise<boolean>;

Defined in: result-builder-async.ts:40

isOk
readonly isOk: Promise<boolean>;

Defined in: result-builder-async.ts:39

map
map: <R>(fn) => AsyncResultBuilder<R, E>;

Defined in: result-builder-async.ts:41

Type Parameters
Type Parameter
R
Parameters
Parameter Type
fn (value) => R
Returns

AsyncResultBuilder<R, E>

mapErr
mapErr: <F>(fn) => AsyncResultBuilder<T, F>;

Defined in: result-builder-async.ts:42

Type Parameters
Type Parameter
F
Parameters
Parameter Type
fn (error) => F
Returns

AsyncResultBuilder<T, F>

match
match: <R>(handlers) => Promise<R>;

Defined in: result-builder-async.ts:59

Type Parameters
Type Parameter
R
Parameters
Parameter Type
handlers { err: (error) => R; ok: (value) => R; }
handlers.err (error) => R
handlers.ok (value) => R
Returns

Promise<R>

note
note: (msg) => AsyncResultBuilder<T, Report<Record<string, unknown>>>;

Defined in: result-builder-async.ts:58

Appends a contextual note to the error. The original message and help are preserved.

Parameters
Parameter Type
msg string
Returns

AsyncResultBuilder<T, Report<Record<string, unknown>>>

orElse
orElse: <F>(fn) => AsyncResultBuilder<T, F>;

Defined in: result-builder-async.ts:44

Type Parameters
Type Parameter
F
Parameters
Parameter Type
fn (error) => | Result<T, F> | AsyncResult<T, F>
Returns

AsyncResultBuilder<T, F>

result
readonly result: AsyncResult<T, E>;

Defined in: result-builder-async.ts:38

tap
tap: (fn) => AsyncResultBuilder<T, E>;

Defined in: result-builder-async.ts:45

Parameters
Parameter Type
fn (value) => void
Returns

AsyncResultBuilder<T, E>

tapErr
tapErr: (fn) => AsyncResultBuilder<T, E>;

Defined in: result-builder-async.ts:46

Parameters
Parameter Type
fn (error) => void
Returns

AsyncResultBuilder<T, E>

unwrap
unwrap: () => Promise<T>;

Defined in: result-builder-async.ts:61

Returns

Promise<T>

unwrapOr
unwrapOr: (defaultValue) => Promise<T>;

Defined in: result-builder-async.ts:60

Parameters
Parameter Type
defaultValue T
Returns

Promise<T>


ResultBuilder

Defined in: result-builder.ts:27

A fluent wrapper around the Result type that allows for method chaining.

Type Parameters

Type Parameter Description
T The type of the success value.
E The type of the error value.

Properties

andThen
andThen: <R>(fn) => ResultBuilder<R, E>;

Defined in: result-builder.ts:56

Chains another operation that returns a Result.

Type Parameters
Type Parameter
R
Parameters
Parameter Type
fn (value) => Result<R, E>
Returns

ResultBuilder<R, E>

context
context: (message, help?, meta?) => ResultBuilder<T, Report<Record<string, unknown>>>;

Defined in: result-builder.ts:94

Attaches context to the error if it exists.

Parameters
Parameter Type
message string
help? string
meta? Record<string, unknown>
Returns

ResultBuilder<T, Report<Record<string, unknown>>>

Deprecated

Use ResultBuilder.note instead, which preserves the original error message and help text while accumulating notes.

isErr
readonly isErr: boolean;

Defined in: result-builder.ts:41

Returns true if the result is an Err.

isOk
readonly isOk: boolean;

Defined in: result-builder.ts:36

Returns true if the result is an Ok.

map
map: <R>(fn) => ResultBuilder<R, E>;

Defined in: result-builder.ts:46

Maps the success value if the result is Ok.

Type Parameters
Type Parameter
R
Parameters
Parameter Type
fn (value) => R
Returns

ResultBuilder<R, E>

mapErr
mapErr: <F>(fn) => ResultBuilder<T, F>;

Defined in: result-builder.ts:51

Maps the error value if the result is Err.

Type Parameters
Type Parameter
F
Parameters
Parameter Type
fn (error) => F
Returns

ResultBuilder<T, F>

match
match: <R>(handlers) => R;

Defined in: result-builder.ts:76

Matches the result against Ok and Err handlers.

Type Parameters
Type Parameter
R
Parameters
Parameter Type
handlers { err: (error) => R; ok: (value) => R; }
handlers.err (error) => R
handlers.ok (value) => R
Returns

R

note
note: (msg) => ResultBuilder<T, Report<Record<string, unknown>>>;

Defined in: result-builder.ts:112

Appends a contextual note to the error.

If the error is already a Report, the note is appended to its notes array. The original message and help are preserved.

Parameters
Parameter Type
msg string
Returns

ResultBuilder<T, Report<Record<string, unknown>>>

Example
build(safe(fn))
  .note("failed to fetch from db")
  .note("user id: 42")
  .unwrapOr(default)
orElse
orElse: <F>(fn) => ResultBuilder<T, F>;

Defined in: result-builder.ts:61

Chains another operation that returns a Result if the current result is an Err.

Type Parameters
Type Parameter
F
Parameters
Parameter Type
fn (error) => Result<T, F>
Returns

ResultBuilder<T, F>

result
readonly result: Result<T, E>;

Defined in: result-builder.ts:31

Returns the underlying raw Result type.

tap
tap: (fn) => ResultBuilder<T, E>;

Defined in: result-builder.ts:66

Executes a side effect if the result is Ok.

Parameters
Parameter Type
fn (value) => void
Returns

ResultBuilder<T, E>

tapErr
tapErr: (fn) => ResultBuilder<T, E>;

Defined in: result-builder.ts:71

Executes a side effect if the result is Err.

Parameters
Parameter Type
fn (error) => void
Returns

ResultBuilder<T, E>

unwrap
unwrap: () => T;

Defined in: result-builder.ts:86

Unwraps the value or throws the error.

Returns

T

unwrapOr
unwrapOr: (defaultValue) => T;

Defined in: result-builder.ts:81

Unwraps the value or returns a default value.

Parameters
Parameter Type
defaultValue T
Returns

T


AsyncResultBuilder

AsyncResultBuilder: {
  all: <V>(results) => AsyncResultBuilder<{ [K in string | number | symbol]: V[K] extends AsyncResult<Val, unknown> ? Val : never }, V[number] extends AsyncResult<unknown, ErrV> ? ErrV : never>;
  any: <U, F>(results) => AsyncResultBuilder<U, F>;
  err: <U, F>(error) => AsyncResultBuilder<U, F>;
  ok: <U, F>(...args) => AsyncResultBuilder<U, F>;
  safeAsync: <U>(promise) => AsyncResultBuilder<U, Error>;
};

Defined in: result-builder-async.ts:37

Namespace object providing convenient static constructors for AsyncResultBuilder.

Use these to start an async fluent chain without manually wrapping values:

await AsyncResultBuilder.ok(42).map(n => n + 1).unwrap()    // 43
await AsyncResultBuilder.safeAsync(fetch("/api/user"))
  .andThen(res => res.json())
  .unwrap()

Under the hood each method wraps the value in a resolved Promise<Result> and delegates to createAsyncResultBuilder.

Type Declaration

Name Type Description Defined in
all() <V>(results) => AsyncResultBuilder<{ [K in string | number | symbol]: V[K] extends AsyncResult<Val, unknown> ? Val : never }, V[number] extends AsyncResult<unknown, ErrV> ? ErrV : never> Combines multiple async Results into a single async builder. Awaits all async results in parallel. Returns Ok with an array of success values, or the first Err encountered. Example await AsyncResultBuilder.all([safeAsync(fetch("/a")), safeAsync(fetch("/b"))]) result-builder-async.ts:246
any() <U, F>(results) => AsyncResultBuilder<U, F> Returns the first Ok async Result from an array. Awaits all async results in parallel. If none succeeded, returns the last error. Throws on an empty array. Example await AsyncResultBuilder.any([safeAsync(fetch("/a")), safeAsync(fetch("/b"))]) result-builder-async.ts:281
err() <U, F>(error) => AsyncResultBuilder<U, F> Creates an AsyncResultBuilder wrapping a resolved Err result. Example await AsyncResultBuilder.err("fail").unwrapOr("default") result-builder-async.ts:223
ok() <U, F>(...args) => AsyncResultBuilder<U, F> Creates an AsyncResultBuilder wrapping a resolved Ok result. Example await AsyncResultBuilder.ok("done").unwrap() // "done" result-builder-async.ts:211
safeAsync() <U>(promise) => AsyncResultBuilder<U, Error> Creates an AsyncResultBuilder from a Promise via safeAsync. Example await AsyncResultBuilder.safeAsync(fetch("/api/user")) result-builder-async.ts:233

ResultBuilder

ResultBuilder: {
  all: <V>(results) => ResultBuilder<{ [K in string | number | symbol]: V[K] extends Result<Val, unknown> ? Val : never }, V[number] extends Result<unknown, ErrV> ? ErrV : never>;
  any: <U, F>(results) => ResultBuilder<U, F>;
  err: <U, F>(error) => ResultBuilder<U, F>;
  ok: <U, F>(...args) => ResultBuilder<U, F>;
  safe: <U>(fn) => ResultBuilder<U, Error>;
};

Defined in: result-builder.ts:27

Namespace object providing convenient static constructors for ResultBuilder.

Use these to start a fluent chain without manually wrapping values in Ok/Err:

ResultBuilder.ok(42).map(n => n + 1).unwrap()    // 43
ResultBuilder.err("fail").unwrapOr("default")     // "default"
ResultBuilder.safe(() => JSON.parse(raw)).unwrap() // parsed value

Under the hood each method delegates to the corresponding factory function and wraps the result in a ResultBuilder via createResultBuilder.

Type Declaration

Name Type Description Defined in
all() <V>(results) => ResultBuilder<{ [K in string | number | symbol]: V[K] extends Result<Val, unknown> ? Val : never }, V[number] extends Result<unknown, ErrV> ? ErrV : never> Combines multiple Results into a single builder via all. Returns Ok with an array of all success values, or the first Err. Example ResultBuilder.all([Ok(1), Ok(2)]).unwrap() // [1, 2] result-builder.ts:215
any() <U, F>(results) => ResultBuilder<U, F> Returns the first Ok Result from an array via any. If all Results are Err, returns the last error. Example ResultBuilder.any([Err("a"), Ok(1)]).unwrap() // 1 result-builder.ts:233
err() <U, F>(error) => ResultBuilder<U, F> Creates a ResultBuilder wrapping a failed Err result. Example ResultBuilder.err("not found").unwrapOr("default") result-builder.ts:194
ok() <U, F>(...args) => ResultBuilder<U, F> Creates a ResultBuilder wrapping a successful Ok result. Example ResultBuilder.ok("hello").map(s => s.length).unwrap() // 5 result-builder.ts:184
safe() <U>(fn) => ResultBuilder<U, Error> Creates a ResultBuilder by wrapping a throwing function with safe. Example ResultBuilder.safe(() => JSON.parse(raw)).unwrap() result-builder.ts:204

build()

function build<T, E>(result): ResultBuilder<T, E>;

Defined in: result-builder.ts:245

Wraps a Result in a ResultBuilder for fluent chaining.

Type Parameters

Type Parameter
T
E

Parameters

Parameter Type Description
result Result<T, E> The Result to wrap.

Returns

ResultBuilder<T, E>

A ResultBuilder instance.


buildAsync()

function buildAsync<T, E>(promise): AsyncResultBuilder<T, E>;

Defined in: result-builder-async.ts:318

Wraps an AsyncResult (Promise<Result<T, E>>) in an AsyncResultBuilder for fluent chaining.

Type Parameters

Type Parameter
T
E

Parameters

Parameter Type Description
promise AsyncResult<T, E> The async result promise to wrap.

Returns

AsyncResultBuilder<T, E>

An AsyncResultBuilder instance.

Example

const value = await buildAsync(safeAsync(fetch("/api/user")))
  .andThen(res => res.json())
  .unwrapOr(null);

createAsyncResultBuilder()

function createAsyncResultBuilder<T, E>(promise, ops?): AsyncResultBuilder<T, E>;

Defined in: result-builder-async.ts:77

Creates an AsyncResultBuilder from a raw AsyncResult (Promise<Result<T, E>>).

Operations are lazily queued and only executed when the builder is consumed (via .unwrap(), .unwrapOr(), .match(), .result, .isOk, or .isErr). This avoids unnecessary promise chains when multiple transforms are composed.

Type Parameters

Type Parameter
T
E

Parameters

Parameter Type Description
promise AsyncResult<T, E> The async result promise to wrap.
ops? Op[] Internal list of queued operations (used when chaining).

Returns

AsyncResultBuilder<T, E>

An AsyncResultBuilder instance.


createResultBuilder()

function createResultBuilder<T, E>(result): ResultBuilder<T, E>;

Defined in: result-builder.ts:127

Creates a ResultBuilder from a raw Result value.

This is the low-level factory used internally by build and ResultBuilder. All operations are evaluated eagerly on the wrapped result.

Type Parameters

Type Parameter
T
E

Parameters

Parameter Type Description
result Result<T, E> The Result<T, E> to wrap.

Returns

ResultBuilder<T, E>

A ResultBuilder instance providing fluent chaining.

Consumers

match()

function match<T, E, R>(result, handlers): R;

Defined in: consumers/match.ts:22

Matches a Result against different handlers for Ok and Err cases. This pattern forces handling both success and failure states, similar to Rust's match.

Type Parameters

Type Parameter Description
T The type of the success value.
E The type of the error value.
R The type of the return value from the handlers.

Parameters

Parameter Type Description
result Result<T, E> The Result to match.
handlers { err: (error) => R; ok: (value) => R; } An object with ok and err functions.
handlers.err (error) => R -
handlers.ok (value) => R -

Returns

R

The result of the appropriate handler.

See

unwrapOr

Example

const output = match(res, {
  ok: (val) => `Success: ${val}`,
  err: (err) => `Failure: ${err}`
});

unwrap()

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

Defined in: consumers/unwrap.ts:18

Unwraps a Result, returning the success value or throwing the error.

Type Parameters

Type Parameter Description
T The type of the success value.
E The type of the error value.

Parameters

Parameter Type Description
result Result<T, E> The Result to unwrap.

Returns

T

The success value.

Throws

The error contained in the Result if it's an Err.

See

unwrapOr

Example

const val = unwrap(Ok(42)); // 42
const val = unwrap(Err("failed")); // throws "failed"

unwrapOr()

function unwrapOr<T, E>(result, defaultValue): T;

Defined in: consumers/unwrap-or.ts:18

Unwraps a Result, returning the contained value if it's Ok, or a default value if it's Err.

Type Parameters

Type Parameter Description
T The type of the success value.
E The type of the error value.

Parameters

Parameter Type Description
result Result<T, E> The Result to unwrap.
defaultValue T The value to return if the Result is an Err.

Returns

T

The contained value if Ok, otherwise the default value.

See

match

Example

const res = Err("error");
const val = unwrapOr(res, "default"); // "default"

Error Handling

ErrFactory()

Defined in: pattern.ts:349

A callable factory that creates typed errors and can participate in matchErr pattern matching.

Create one via createError or createErrors()[key].

Type Parameters

Type Parameter Default type Description
A extends unknown[] - The type of the arguments tuple passed to the factory.
N extends string - The literal string type of the error name (.kind / .name).
M Record<string, unknown> The type of the static metadata attached to each error.
ErrFactory(...args): TypedError<A, N, M>;

Defined in: pattern.ts:350

A callable factory that creates typed errors and can participate in matchErr pattern matching.

Create one via createError or createErrors()[key].

Parameters

Parameter Type
...args A

Returns

TypedError<A, N, M>

Properties

[$class]
readonly [$class]: symbol;

Defined in: pattern.ts:351


MatchErrBuilder

Defined in: pattern.ts:232

Fluent builder for pattern matching on a Result's error.

Start with matchErr, then chain .on() calls for each error variant you want to handle, and finish with .otherwise() or .exhaustive().

Type Parameters

Type Parameter Default type Description
T - The success type of the Result being matched.
E - The error type of the Result being matched.
R - The accumulated return type of all .on() handlers.
Handled extends string never The union of error kinds already handled (tracked at type level).

Properties

exhaustive
exhaustive: () => [Exclude<TypedKinds<E>, Handled>] extends [never] ? T | R : MissingHandler<Exclude<TypedKinds<E>, Handled>>;

Defined in: pattern.ts:260

Ensures all typed errors from a createErrors set are handled.

If not all error kinds are handled, TypeScript will show an error like MissingHandler<"DbError"> indicating exactly which handler is missing.

Returns

[Exclude<TypedKinds<E>, Handled>] extends [never] ? T | R : MissingHandler<Exclude<TypedKinds<E>, Handled>>

otherwise
otherwise: (fallback) => T | R;

Defined in: pattern.ts:252

Finalizes the match with a fallback for unhandled errors.

Parameters
Parameter Type
fallback (err) => R
Returns

T | R

Methods

on()
Call Signature
on<A, N, M, HandlerResult>(def, handler): MatchErrBuilder<T, E, R | HandlerResult, Handled | N>;

Defined in: pattern.ts:236

Handles a specific error kind.

Type Parameters
Type Parameter
A extends unknown[]
N extends string
M
HandlerResult
Parameters
Parameter Type
def ErrFactory<A, N, M>
handler (err) => HandlerResult
Returns

MatchErrBuilder<T, E, R | HandlerResult, Handled | N>

Call Signature
on<C, HandlerResult>(def, handler): MatchErrBuilder<T, E, R | HandlerResult, Handled>;

Defined in: pattern.ts:244

Handles an external error class.

Type Parameters
Type Parameter
C extends (...args) => Error
HandlerResult
Parameters
Parameter Type
def ExternalErrFactory<C>
handler (err) => HandlerResult
Returns

MatchErrBuilder<T, E, R | HandlerResult, Handled>


Report

Defined in: report.ts:25

A structured error object that supports causes, help messages, and context. Inspired by Rust's anyhow or eyre.

Type Parameters

Type Parameter Default type Description
C extends Record<string, unknown> Record<string, unknown> The type of the context metadata.

Properties

cause?
optional cause?: unknown;

Defined in: report.ts:37

The underlying cause of the error.

context?
optional context?: C;

Defined in: report.ts:33

Additional key-value pairs to provide more context.

help?
optional help?: string;

Defined in: report.ts:31

A helpful message for the user on how to resolve the error.

message
message: string;

Defined in: report.ts:29

The error message.

name
name: "Report";

Defined in: report.ts:27

The error name, always "Report".

notes?
optional notes?: string[];

Defined in: report.ts:35

A list of contextual notes accumulated during error propagation.

stack?
optional stack?: string;

Defined in: report.ts:39

The stack trace.


ReportOptions

Defined in: report.ts:7

Options for creating a new Report.

Type Parameters

Type Parameter Default type Description
C extends Record<string, unknown> Record<string, unknown> The type of the context metadata.

Properties

cause?
optional cause?: unknown;

Defined in: report.ts:9

The underlying cause of the error.

context?
optional context?: C;

Defined in: report.ts:13

Additional key-value pairs to provide more context.

help?
optional help?: string;

Defined in: report.ts:11

A helpful message for the user on how to resolve the error.

notes?
optional notes?: string[];

Defined in: report.ts:15

A list of contextual notes accumulated during error propagation.


createError()

function createError<A, N, M>(
   name, 
   message, 
   help?, 
_metadata?): ErrFactory<A, N, M>;

Defined in: pattern.ts:154

Creates a single typed error factory.

Returns a callable function that produces TypedError objects with a discriminable .kind field, optional help text, and arbitrary metadata. The returned factory also acts as a matcher for matchErr.

Type Parameters

Type Parameter Default type Description
A extends unknown[] - The type of the arguments tuple.
N extends string - The literal string type of the error name.
M Record<string, unknown> The type of the static metadata.

Parameters

Parameter Type Description
name N The literal error name (used as .kind and err.name).
message (...args) => string A message template receiving the same args as the factory.
help? (...args) => string An optional help template for user-facing guidance.
_metadata? M Optional static metadata attached to every produced error.

Returns

ErrFactory<A, N, M>

An ErrFactory that creates typed errors and can be passed to matchErr .on() for instanceof-style matching.

See

  • createErrors
  • matchErr

Example

const NotFound = createError(
  "NotFound",
  (id: string) => `User "${id}" not found`,
  (id: string) => `Check user ID "${id}"`,
);

const err = NotFound("42");
err.kind   // "NotFound"
err.args   // ["42"]
err.help   // "Check user ID \"42\""

createErrors()

function createErrors<T>(defs): ErrorFactories<T>;

Defined in: pattern.ts:110

Creates a collection of error factories from a definition map.

Each key becomes a named ErrFactory callable with the args inferred from the message function. The returned object also carries a _type discriminant — a union of all defined error types — useful for exhaustive type narrowing and for annotating Result<E, AppError>.

Inspired by Rust's thiserror / derive(Error) pattern.

Type Parameters

Type Parameter Description
T extends ErrDefMap The shape of the definition map.

Parameters

Parameter Type Description
defs T An object mapping error names to { message, help?, _metadata? }.

Returns

ErrorFactories<T>

An object with one factory per key and a combined _type union.

See

  • createError
  • matchErr

Example

const Errors = createErrors({
  NotFound: { message: (id: string) => `User "${id}" not found` },
  DbError:  { message: (code: number) => `Database error ${code}` },
});

type AppError = typeof Errors._type;
// AppError = TypedError<[string], "NotFound"> | TypedError<[number], "DbError">

const err = Errors.NotFound("42");
err.kind // "NotFound"

matchErr()

function matchErr<T, E>(result): MatchErrBuilder<T, E, never, never>;

Defined in: pattern.ts:285

Starts a fluent pattern match on a Result's error.

Chain .on() calls for each error variant you want to handle, then finish with .otherwise(fallback) for a catch-all or .exhaustive() when every possible typed error kind has a handler.

When the Result is Ok, the match short-circuits and returns the success value directly — no handler is invoked.

Type Parameters

Type Parameter
T
E

Parameters

Parameter Type Description
result Result<T, E> The Result whose error to match against.

Returns

MatchErrBuilder<T, E, never, never>

A MatchErrBuilder to chain .on() calls.

Example

matchErr(getUser("123"))
  .on(NotFound, (e) => `Missing user ${e.args[0]}`)
  .on(DbError,  (e) => `DB error code ${e.args[0]}`)
  .exhaustive();

wrapError()

function wrapError<C>(cls): ExternalErrFactory<C>;

Defined in: pattern.ts:209

Wraps an external Error class so it can be matched with matchErr.

The returned factory creates instances of the original class, and the .on() handler in matchErr uses instanceof under the hood, so you get full access to the original class's typed properties.

Type Parameters

Type Parameter
C extends (...args) => Error

Parameters

Parameter Type Description
cls C The external Error class to wrap (e.g. PrismaClientKnownRequestError).

Returns

ExternalErrFactory<C>

An ExternalErrFactory callable as a constructor and usable in matchErr .on().

Example

import { PrismaClientKnownRequestError } from "@prisma/client";
const PrismaErr = wrapError(PrismaClientKnownRequestError);

matchErr(result)
  .on(PrismaErr, (e) => `Prisma error ${e.code}`)
  .otherwise((e) => `Other: ${e.message}`);

Factories

bail()

function bail(message, options?): Report;

Defined in: factories/bail.ts:15

Creates a new Report instance. Useful for generating structured errors to be wrapped in an Err result.

Parameters

Parameter Type Description
message string The error message.
options? ReportOptions<Record<string, unknown>> Additional report options.

Returns

Report

A new Report instance.

Example

return Err(bail("Permission denied", { help: "Check your API token" }));

Err()

function Err<T, E>(error): Result<T, E>;

Defined in: factories/err.ts:17

Constructs an error Result containing the given error.

Type Parameters

Type Parameter Description
T The type of the success value.
E The type of the error value.

Parameters

Parameter Type Description
error E The error to wrap in an Err result.

Returns

Result<T, E>

A failed Result object { ok: false, error: E }.

See

Ok

Example

const res = Err("Something went wrong");
if (!res.ok) console.error(res.error); // "Something went wrong"

isErr()

function isErr<T, E>(result): result is { error: E; ok: false };

Defined in: factories/is-err.ts:17

A type guard that checks if a Result is an Err.

Type Parameters

Type Parameter Description
T The type of the success value.
E The type of the error value.

Parameters

Parameter Type Description
result Result<T, E> The Result to check.

Returns

result is { error: E; ok: false }

true if the result is an Err, false otherwise.

Example

if (isErr(res)) {
  console.error(res.error); // res.error is typed as E
}

isOk()

function isOk<T, E>(result): result is { ok: true; value: T };

Defined in: factories/is-ok.ts:17

A type guard that checks if a Result is an Ok.

Type Parameters

Type Parameter Description
T The type of the success value.
E The type of the error value.

Parameters

Parameter Type Description
result Result<T, E> The Result to check.

Returns

result is { ok: true; value: T }

true if the result is an Ok, false otherwise.

Example

if (isOk(res)) {
  console.log(res.value); // res.value is typed as T
}

Ok()

function Ok<T, E>(...args): Result<T, E>;

Defined in: factories/ok.ts:17

Constructs a successful Result containing the given value.

Type Parameters

Type Parameter Default type Description
T void The type of the success value.
E unknown The type of the error value.

Parameters

Parameter Type Description
...args undefined extends T ? [T?] : [T] The value to wrap in an Ok result. Required if T is not void.

Returns

Result<T, E>

A successful Result object { ok: true, value: T }.

See

Err

Example

const res = Ok(42);
if (res.ok) console.log(res.value); // 42

safe()

function safe<T, E>(fn): Result<T, E>;

Defined in: factories/safe.ts:20

Executes a synchronous function and wraps its return value in an Ok result. If the function throws an error, it captures it and wraps it in an Err result.

Type Parameters

Type Parameter Default type Description
T - The type of the success value.
E Error The type of the error value. Defaults to Error.

Parameters

Parameter Type Description
fn () => T The function to execute.

Returns

Result<T, E>

An Ok result with the return value, or an Err result with the thrown error.

See

safeAsync

Example

const res = safe(() => JSON.parse('{"valid": true}'));
if (res.ok) console.log(res.value);

safeAsync()

function safeAsync<T, E>(promise): Promise<Result<T, E>>;

Defined in: factories/safe-async.ts:21

Converts a Promise into a Result. If the promise resolves, it returns an Ok result with the data. If the promise rejects, it captures the reason and returns an Err result.

Type Parameters

Type Parameter Default type Description
T - The type of the success value.
E Error The type of the error value. Defaults to Error.

Parameters

Parameter Type Description
promise Promise<T> The Promise to convert.

Returns

Promise<Result<T, E>>

A Promise resolving to an Ok result with the data, or an Err result with the error.

See

safe

Example

const res = await safeAsync(fetch("https://api.example.com"));
if (res.ok) console.log(await res.value.json());

Operators

andThen()

function andThen<T, E, R>(result, fn): Result<R, E>;

Defined in: operators/and-then.ts:23

Chains a sequence of operations that may fail, short-circuiting on the first error. If the Result is an Ok, it applies the function to the value and returns its Result. If the Result is an Err, it returns the original error without executing the function.

Also known as flatMap or bind in other functional contexts.

Type Parameters

Type Parameter Description
T The type of the success value.
E The type of the error value.
R The type of the new success value.

Parameters

Parameter Type Description
result Result<T, E> The initial Result.
fn (value) => Result<R, E> The function to apply to the success value if it's Ok.

Returns

Result<R, E>

A new Result representing the chained operation.

See

map

Example

const res = Ok("user_id");
const user = andThen(res, fetchUser); // fetchUser returns a Result

context()

function context<T, E, C>(
   result, 
   message, 
   help?, 
meta?): Result<T, Report<C>>;

Defined in: operators/context.ts:26

Attaches context to a Result's error, converting it to a Report if it isn't one already.

Type Parameters

Type Parameter Default type Description
T - The type of the success value.
E - The type of the error value.
C extends Record<string, unknown> Record<string, unknown> The type of the metadata.

Parameters

Parameter Type Description
result Result<T, E> The Result to attach context to.
message string The context message.
help? string An optional help message.
meta? C Optional metadata to attach (merged with any _metadata from the original error).

Returns

Result<T, Report<C>>

A Result with the same success value or a Report as the error.

Deprecated

Use note() to add contextual information without overwriting the error message, or use mapErr() + createReport() / reportFrom() for full control. Unlike context(), note() preserves the original message and help, and supports accumulating multiple notes via an array.

Example

const res = context(safe(() => JSON.parse(data)), "Failed to parse config");

map()

function map<T, E, R>(result, fn): Result<R, E>;

Defined in: operators/map.ts:22

Maps a Result's success value using the provided function, leaving errors unchanged. If the Result is an Err, the function is not executed and the original error is returned.

Type Parameters

Type Parameter Description
T The type of the success value.
E The type of the error value.
R The type of the new success value.

Parameters

Parameter Type Description
result Result<T, E> The Result to map.
fn (value) => R The function to apply to the success value if it's Ok.

Returns

Result<R, E>

A new Result with the mapped success value or the original error.

See

  • mapErr
  • andThen

Example

const res = Ok(1);
const doubled = map(res, (n) => n * 2); // Ok(2)

mapErr()

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

Defined in: operators/map-err.ts:22

Maps a Result's error value using the provided function, leaving successes unchanged. If the Result is an Ok, the function is not executed and the original success value is returned.

Type Parameters

Type Parameter Description
T The type of the success value.
E The type of the error value.
F The type of the new error value.

Parameters

Parameter Type Description
result Result<T, E> The Result to map.
fn (error) => F The function to apply to the error value if it's Err.

Returns

Result<T, F>

A new Result with the mapped error value or the original success.

See

  • map
  • orElse

Example

const res = Err("not found");
const wrapped = mapErr(res, (e) => new Error(e)); // Err(Error("not found"))

note()

function note<T, E>(result, msg): Result<T, Report<Record<string, unknown>>>;

Defined in: operators/note.ts:27

Appends a contextual note to a Result's error.

If the error is already a Report, the note is appended to its notes array. Otherwise, the error is wrapped in a Report with the note as the first entry. The original error's message and help are preserved.

Type Parameters

Type Parameter Description
T The type of the success value.
E The type of the error value.

Parameters

Parameter Type Description
result Result<T, E> The Result to attach a note to.
msg string The note message to append.

Returns

Result<T, Report<Record<string, unknown>>>

A Result with the same success value or a Report with the appended note.

Example

const res = build(safe(fn))
  .mapErr(err => note(err, "failed to fetch from db"))
  .mapErr(err => note(err, "user id: 42"))
  .unwrapOr(default);
// res.error.notes → ["failed to fetch from db", "user id: 42"]

orElse()

function orElse<T, E, F>(result, fn): Result<T, F>;

Defined in: operators/or-else.ts:21

Chains a sequence of operations that may fail, allowing recovery from errors. If the Result is an Err, it applies the function to the error and returns its Result. If the Result is an Ok, it returns the original success value without executing the function.

Type Parameters

Type Parameter Description
T The type of the success value.
E The type of the error value.
F The type of the new error value.

Parameters

Parameter Type Description
result Result<T, E> The initial Result.
fn (error) => Result<T, F> The function to apply to the error value if it's Err.

Returns

Result<T, F>

A new Result representing the chained operation with potential recovery.

See

mapErr

Example

const res = Err("failed");
const recovered = orElse(res, () => Ok("default")); // Ok("default")

tap()

function tap<T, E>(result, fn): Result<T, E>;

Defined in: operators/tap.ts:18

Executes a side effect function if the Result is an Ok. The original Result is returned unchanged.

Type Parameters

Type Parameter Description
T The type of the success value.
E The type of the error value.

Parameters

Parameter Type Description
result Result<T, E> The Result to tap into.
fn (value) => void The function to execute with the success value.

Returns

Result<T, E>

The original Result unchanged.

See

tapErr

Example

map(res, val => val + 1).tap(val => console.log(val))

tapErr()

function tapErr<T, E>(result, fn): Result<T, E>;

Defined in: operators/tap-err.ts:18

Executes a side effect function if the Result is an Err. The original Result is returned unchanged.

Type Parameters

Type Parameter Description
T The type of the success value.
E The type of the error value.

Parameters

Parameter Type Description
result Result<T, E> The Result to tap into.
fn (error) => void The function to execute with the error value.

Returns

Result<T, E>

The original Result unchanged.

See

tap

Example

safe(() => doSomething()).tapErr(err => logger.error(err))

Other

AsyncResult

type AsyncResult<T, E> = Promise<Result<T, E>>;

Defined in: types/result.ts:15

Represents a Result that is asynchronously resolved.

Type Parameters

Type Parameter Description
T The type of the success value.
E The type of the error value.

Result

type Result<T, E> = 
  | {
  ok: true;
  value: T;
}
  | {
  error: E;
  ok: false;
};

Defined in: types/result.ts:7

A Result type representing either a success (Ok) or an error (Err).

Type Parameters

Type Parameter Description
T The type of the success value.
E The type of the error value.

createReport()

function createReport<C>(message, options?): Report<C>;

Defined in: report.ts:49

Creates a new Report instance.

Type Parameters

Type Parameter Default type
C extends Record<string, unknown> Record<string, unknown>

Parameters

Parameter Type Description
message string The error message.
options ReportOptions<C> Additional options for the report.

Returns

Report<C>

A new Report object.


isReport()

function isReport(err): err is Report<Record<string, unknown>>;

Defined in: report.ts:79

Checks if a value is a Report.

Parameters

Parameter Type Description
err unknown The value to check.

Returns

err is Report<Record<string, unknown>>

True if the value is a Report.


reportFrom()

function reportFrom<T>(
   err, 
   message?, 
options?): Report<T>;

Defined in: report.ts:92

Creates a Report from an unknown error. If the error is already a Report and no new information is provided, it returns it as is.

Type Parameters

Type Parameter Default type
T extends Record<string, unknown> Record<string, unknown>

Parameters

Parameter Type Description
err unknown The original error.
message? string An optional new message.
options? ReportOptions<T> Additional options.

Returns

Report<T>

A Report instance.

Utilities

all()

function all<T>(results): Result<{ [K in string | number | symbol]: T[K] extends Result<Val, unknown> ? Val : never }, T[number] extends Result<unknown, ErrV> ? ErrV : never>;

Defined in: utils/all.ts:19

Combines multiple Results into a single Result. If all Results are Ok, returns an Ok with an array of all values. If any Result is an Err, returns the first Err encountered.

Type Parameters

Type Parameter Description
T extends readonly Result<unknown, unknown>[] The type of the input Results array.

Parameters

Parameter Type Description
results [...T[]] An array of Results to combine.

Returns

Result<{ [K in string | number | symbol]: T[K] extends Result<Val, unknown> ? Val : never }, T[number] extends Result<unknown, ErrV> ? ErrV : never>

A Result with an array of values or the first error.

See

any

Example

const res = all([Ok(1), Ok("a")]); // Result<[number, string], any>

any()

function any<T, E>(results): Result<T, E>;

Defined in: utils/any.ts:18

Returns the first Ok Result from an array of Results. If all Results are Err, returns the last Err encountered (or a default error if empty).

Type Parameters

Type Parameter Description
T The type of the success value.
E The type of the error value.

Parameters

Parameter Type Description
results Result<T, E>[] An array of Results to check.

Returns

Result<T, E>

The first Ok result or the last Err.

See

all

Example

const res = any([Err("a"), Ok(1), Ok(2)]); // Ok(1)

kindOf()

function kindOf(err): string | undefined;

Defined in: utils/kind-of.ts:13

Extracts the error kind from any ripthrow error. Handles TypedError directly and Report (traverses cause).

Parameters

Parameter Type Description
err unknown The error to extract the kind from.

Returns

string | undefined

The error kind string, or undefined if not found.

Example

const kind = kindOf(err);
if (kind === "userNotFound") { ... }

pipe()

Call Signature

function pipe<T>(value): Promise<Awaited<T>>;

Defined in: utils/pipe.ts:13

Pipes a value through a series of transform functions. Accepts both sync and Promise values — awaits the input if needed.

Type Parameters
Type Parameter
T
Parameters
Parameter Type
value T | Promise<T>
Returns

Promise<Awaited<T>>

Example
const result = await pipe(
  safe(() => JSON.parse(input)),
  (r) => map(r, (data: any) => data.a),
  (r) => unwrapOr(r, 0),
);

Call Signature

function pipe<T, F1>(value, f1): Promise<Awaited<F1>>;

Defined in: utils/pipe.ts:14

Pipes a value through a series of transform functions. Accepts both sync and Promise values — awaits the input if needed.

Type Parameters
Type Parameter
T
F1
Parameters
Parameter Type
value T | Promise<T>
f1 (arg) => F1
Returns

Promise<Awaited<F1>>

Example
const result = await pipe(
  safe(() => JSON.parse(input)),
  (r) => map(r, (data: any) => data.a),
  (r) => unwrapOr(r, 0),
);

Call Signature

function pipe<T, F1, F2>(
   value, 
   f1, 
f2): Promise<Awaited<F2>>;

Defined in: utils/pipe.ts:15

Pipes a value through a series of transform functions. Accepts both sync and Promise values — awaits the input if needed.

Type Parameters
Type Parameter
T
F1
F2
Parameters
Parameter Type
value T | Promise<T>
f1 (arg) => F1
f2 (arg) => F2
Returns

Promise<Awaited<F2>>

Example
const result = await pipe(
  safe(() => JSON.parse(input)),
  (r) => map(r, (data: any) => data.a),
  (r) => unwrapOr(r, 0),
);

Call Signature

function pipe<T, F1, F2, F3>(
   value, 
   f1, 
   f2, 
f3): Promise<Awaited<F3>>;

Defined in: utils/pipe.ts:20

Pipes a value through a series of transform functions. Accepts both sync and Promise values — awaits the input if needed.

Type Parameters
Type Parameter
T
F1
F2
F3
Parameters
Parameter Type
value T | Promise<T>
f1 (arg) => F1
f2 (arg) => F2
f3 (arg) => F3
Returns

Promise<Awaited<F3>>

Example
const result = await pipe(
  safe(() => JSON.parse(input)),
  (r) => map(r, (data: any) => data.a),
  (r) => unwrapOr(r, 0),
);

Call Signature

function pipe<T, F1, F2, F3, F4>(
   value, 
   f1, 
   f2, 
   f3, 
f4): Promise<Awaited<F4>>;

Defined in: utils/pipe.ts:27

Pipes a value through a series of transform functions. Accepts both sync and Promise values — awaits the input if needed.

Type Parameters
Type Parameter
T
F1
F2
F3
F4
Parameters
Parameter Type
value T | Promise<T>
f1 (arg) => F1
f2 (arg) => F2
f3 (arg) => F3
f4 (arg) => F4
Returns

Promise<Awaited<F4>>

Example
const result = await pipe(
  safe(() => JSON.parse(input)),
  (r) => map(r, (data: any) => data.a),
  (r) => unwrapOr(r, 0),
);

Call Signature

function pipe<T, F1, F2, F3, F4, F5>(
   value, 
   f1, 
   f2, 
   f3, 
   f4, 
f5): Promise<Awaited<F5>>;

Defined in: utils/pipe.ts:35

Pipes a value through a series of transform functions. Accepts both sync and Promise values — awaits the input if needed.

Type Parameters
Type Parameter
T
F1
F2
F3
F4
F5
Parameters
Parameter Type
value T | Promise<T>
f1 (arg) => F1
f2 (arg) => F2
f3 (arg) => F3
f4 (arg) => F4
f5 (arg) => F5
Returns

Promise<Awaited<F5>>

Example
const result = await pipe(
  safe(() => JSON.parse(input)),
  (r) => map(r, (data: any) => data.a),
  (r) => unwrapOr(r, 0),
);

Clone this wiki locally