-
Notifications
You must be signed in to change notification settings - Fork 0
API Reference
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.
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 Parameter | Description |
|---|---|
T |
The success type. |
E |
The error type. |
andThen: <R>(fn) => AsyncResultBuilder<R, E>;Defined in: result-builder-async.ts:43
| Type Parameter |
|---|
R |
| Parameter | Type |
|---|---|
fn |
(value) => | Result<R, E> | AsyncResult<R, E> |
AsyncResultBuilder<R, E>
context: <C>(message, help?, meta?) => AsyncResultBuilder<T, Report<C>>;Defined in: result-builder-async.ts:48
| Type Parameter |
|---|
C extends Record<string, unknown> |
| Parameter | Type |
|---|---|
message |
string |
help? |
string |
meta? |
C |
AsyncResultBuilder<T, Report<C>>
Use AsyncResultBuilder.note instead.
readonly isErr: Promise<boolean>;Defined in: result-builder-async.ts:40
readonly isOk: Promise<boolean>;Defined in: result-builder-async.ts:39
map: <R>(fn) => AsyncResultBuilder<R, E>;Defined in: result-builder-async.ts:41
| Type Parameter |
|---|
R |
| Parameter | Type |
|---|---|
fn |
(value) => R
|
AsyncResultBuilder<R, E>
mapErr: <F>(fn) => AsyncResultBuilder<T, F>;Defined in: result-builder-async.ts:42
| Type Parameter |
|---|
F |
| Parameter | Type |
|---|---|
fn |
(error) => F
|
AsyncResultBuilder<T, F>
match: <R>(handlers) => Promise<R>;Defined in: result-builder-async.ts:59
| Type Parameter |
|---|
R |
| Parameter | Type |
|---|---|
handlers |
{ err: (error) => R; ok: (value) => R; } |
handlers.err |
(error) => R
|
handlers.ok |
(value) => R
|
Promise<R>
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.
| Parameter | Type |
|---|---|
msg |
string |
AsyncResultBuilder<T, Report<Record<string, unknown>>>
orElse: <F>(fn) => AsyncResultBuilder<T, F>;Defined in: result-builder-async.ts:44
| Type Parameter |
|---|
F |
| Parameter | Type |
|---|---|
fn |
(error) => | Result<T, F> | AsyncResult<T, F> |
AsyncResultBuilder<T, F>
readonly result: AsyncResult<T, E>;Defined in: result-builder-async.ts:38
tap: (fn) => AsyncResultBuilder<T, E>;Defined in: result-builder-async.ts:45
| Parameter | Type |
|---|---|
fn |
(value) => void
|
AsyncResultBuilder<T, E>
tapErr: (fn) => AsyncResultBuilder<T, E>;Defined in: result-builder-async.ts:46
| Parameter | Type |
|---|---|
fn |
(error) => void
|
AsyncResultBuilder<T, E>
unwrap: () => Promise<T>;Defined in: result-builder-async.ts:61
Promise<T>
unwrapOr: (defaultValue) => Promise<T>;Defined in: result-builder-async.ts:60
| Parameter | Type |
|---|---|
defaultValue |
T |
Promise<T>
Defined in: result-builder.ts:27
A fluent wrapper around the Result type that allows for method chaining.
| Type Parameter | Description |
|---|---|
T |
The type of the success value. |
E |
The type of the error value. |
andThen: <R>(fn) => ResultBuilder<R, E>;Defined in: result-builder.ts:56
Chains another operation that returns a Result.
| Type Parameter |
|---|
R |
| Parameter | Type |
|---|---|
fn |
(value) => Result<R, E> |
ResultBuilder<R, E>
context: (message, help?, meta?) => ResultBuilder<T, Report<Record<string, unknown>>>;Defined in: result-builder.ts:94
Attaches context to the error if it exists.
| Parameter | Type |
|---|---|
message |
string |
help? |
string |
meta? |
Record<string, unknown> |
ResultBuilder<T, Report<Record<string, unknown>>>
Use ResultBuilder.note instead, which preserves the original error message and help text while accumulating notes.
readonly isErr: boolean;Defined in: result-builder.ts:41
Returns true if the result is an Err.
readonly isOk: boolean;Defined in: result-builder.ts:36
Returns true if the result is an Ok.
map: <R>(fn) => ResultBuilder<R, E>;Defined in: result-builder.ts:46
Maps the success value if the result is Ok.
| Type Parameter |
|---|
R |
| Parameter | Type |
|---|---|
fn |
(value) => R
|
ResultBuilder<R, E>
mapErr: <F>(fn) => ResultBuilder<T, F>;Defined in: result-builder.ts:51
Maps the error value if the result is Err.
| Type Parameter |
|---|
F |
| Parameter | Type |
|---|---|
fn |
(error) => F
|
ResultBuilder<T, F>
match: <R>(handlers) => R;Defined in: result-builder.ts:76
Matches the result against Ok and Err handlers.
| Type Parameter |
|---|
R |
| Parameter | Type |
|---|---|
handlers |
{ err: (error) => R; ok: (value) => R; } |
handlers.err |
(error) => R
|
handlers.ok |
(value) => R
|
R
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.
| Parameter | Type |
|---|---|
msg |
string |
ResultBuilder<T, Report<Record<string, unknown>>>
build(safe(fn))
.note("failed to fetch from db")
.note("user id: 42")
.unwrapOr(default)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 Parameter |
|---|
F |
| Parameter | Type |
|---|---|
fn |
(error) => Result<T, F> |
ResultBuilder<T, F>
readonly result: Result<T, E>;Defined in: result-builder.ts:31
Returns the underlying raw Result type.
tap: (fn) => ResultBuilder<T, E>;Defined in: result-builder.ts:66
Executes a side effect if the result is Ok.
| Parameter | Type |
|---|---|
fn |
(value) => void
|
ResultBuilder<T, E>
tapErr: (fn) => ResultBuilder<T, E>;Defined in: result-builder.ts:71
Executes a side effect if the result is Err.
| Parameter | Type |
|---|---|
fn |
(error) => void
|
ResultBuilder<T, E>
unwrap: () => T;Defined in: result-builder.ts:86
Unwraps the value or throws the error.
T
unwrapOr: (defaultValue) => T;Defined in: result-builder.ts:81
Unwraps the value or returns a default value.
| Parameter | Type |
|---|---|
defaultValue |
T |
T
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.
| 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: {
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 valueUnder the hood each method delegates to the corresponding factory function
and wraps the result in a ResultBuilder via createResultBuilder.
| 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 |
function build<T, E>(result): ResultBuilder<T, E>;Defined in: result-builder.ts:245
Wraps a Result in a ResultBuilder for fluent chaining.
| Type Parameter |
|---|
T |
E |
| Parameter | Type | Description |
|---|---|---|
result |
Result<T, E> |
The Result to wrap. |
ResultBuilder<T, E>
A ResultBuilder instance.
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 Parameter |
|---|
T |
E |
| Parameter | Type | Description |
|---|---|---|
promise |
AsyncResult<T, E> |
The async result promise to wrap. |
AsyncResultBuilder<T, E>
An AsyncResultBuilder instance.
const value = await buildAsync(safeAsync(fetch("/api/user")))
.andThen(res => res.json())
.unwrapOr(null);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 Parameter |
|---|
T |
E |
| Parameter | Type | Description |
|---|---|---|
promise |
AsyncResult<T, E> |
The async result promise to wrap. |
ops? |
Op[] |
Internal list of queued operations (used when chaining). |
AsyncResultBuilder<T, E>
An AsyncResultBuilder instance.
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 Parameter |
|---|
T |
E |
| Parameter | Type | Description |
|---|---|---|
result |
Result<T, E> |
The Result<T, E> to wrap. |
ResultBuilder<T, E>
A ResultBuilder instance providing fluent chaining.
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 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. |
| 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
|
- |
R
The result of the appropriate handler.
unwrapOr
const output = match(res, {
ok: (val) => `Success: ${val}`,
err: (err) => `Failure: ${err}`
});function unwrap<T, E>(result): T;Defined in: consumers/unwrap.ts:18
Unwraps a Result, returning the success value or throwing the error.
| Type Parameter | Description |
|---|---|
T |
The type of the success value. |
E |
The type of the error value. |
| Parameter | Type | Description |
|---|---|---|
result |
Result<T, E> |
The Result to unwrap. |
T
The success value.
The error contained in the Result if it's an Err.
unwrapOr
const val = unwrap(Ok(42)); // 42
const val = unwrap(Err("failed")); // throws "failed"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 Parameter | Description |
|---|---|
T |
The type of the success value. |
E |
The type of the error value. |
| Parameter | Type | Description |
|---|---|---|
result |
Result<T, E> |
The Result to unwrap. |
defaultValue |
T |
The value to return if the Result is an Err. |
T
The contained value if Ok, otherwise the default value.
match
const res = Err("error");
const val = unwrapOr(res, "default"); // "default"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 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].
| Parameter | Type |
|---|---|
...args
|
A |
TypedError<A, N, M>
readonly [$class]: symbol;Defined in: pattern.ts:351
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 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). |
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.
[Exclude<TypedKinds<E>, Handled>] extends [never] ? T | R : MissingHandler<Exclude<TypedKinds<E>, Handled>>
otherwise: (fallback) => T | R;Defined in: pattern.ts:252
Finalizes the match with a fallback for unhandled errors.
| Parameter | Type |
|---|---|
fallback |
(err) => R
|
T | R
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 Parameter |
|---|
A extends unknown[] |
N extends string
|
M |
HandlerResult |
| Parameter | Type |
|---|---|
def |
ErrFactory<A, N, M> |
handler |
(err) => HandlerResult
|
MatchErrBuilder<T, E, R | HandlerResult, Handled | N>
on<C, HandlerResult>(def, handler): MatchErrBuilder<T, E, R | HandlerResult, Handled>;Defined in: pattern.ts:244
Handles an external error class.
| Type Parameter |
|---|
C extends (...args) => Error
|
HandlerResult |
| Parameter | Type |
|---|---|
def |
ExternalErrFactory<C> |
handler |
(err) => HandlerResult
|
MatchErrBuilder<T, E, R | HandlerResult, Handled>
Defined in: report.ts:25
A structured error object that supports causes, help messages, and context.
Inspired by Rust's anyhow or eyre.
| Type Parameter | Default type | Description |
|---|---|---|
C extends Record<string, unknown> |
Record<string, unknown> |
The type of the context metadata. |
optional cause?: unknown;Defined in: report.ts:37
The underlying cause of the error.
optional context?: C;Defined in: report.ts:33
Additional key-value pairs to provide more context.
optional help?: string;Defined in: report.ts:31
A helpful message for the user on how to resolve the error.
message: string;Defined in: report.ts:29
The error message.
name: "Report";Defined in: report.ts:27
The error name, always "Report".
optional notes?: string[];Defined in: report.ts:35
A list of contextual notes accumulated during error propagation.
optional stack?: string;Defined in: report.ts:39
The stack trace.
Defined in: report.ts:7
Options for creating a new Report.
| Type Parameter | Default type | Description |
|---|---|---|
C extends Record<string, unknown> |
Record<string, unknown> |
The type of the context metadata. |
optional cause?: unknown;Defined in: report.ts:9
The underlying cause of the error.
optional context?: C;Defined in: report.ts:13
Additional key-value pairs to provide more context.
optional help?: string;Defined in: report.ts:11
A helpful message for the user on how to resolve the error.
optional notes?: string[];Defined in: report.ts:15
A list of contextual notes accumulated during error propagation.
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 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. |
| 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. |
ErrFactory<A, N, M>
An ErrFactory that creates typed errors and can be passed
to matchErr .on() for instanceof-style matching.
- createErrors
- matchErr
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\""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 Parameter | Description |
|---|---|
T extends ErrDefMap
|
The shape of the definition map. |
| Parameter | Type | Description |
|---|---|---|
defs |
T |
An object mapping error names to { message, help?, _metadata? }. |
ErrorFactories<T>
An object with one factory per key and a combined _type union.
- createError
- matchErr
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"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 Parameter |
|---|
T |
E |
| Parameter | Type | Description |
|---|---|---|
result |
Result<T, E> |
The Result whose error to match against. |
MatchErrBuilder<T, E, never, never>
A MatchErrBuilder to chain .on() calls.
matchErr(getUser("123"))
.on(NotFound, (e) => `Missing user ${e.args[0]}`)
.on(DbError, (e) => `DB error code ${e.args[0]}`)
.exhaustive();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 Parameter |
|---|
C extends (...args) => Error
|
| Parameter | Type | Description |
|---|---|---|
cls |
C |
The external Error class to wrap (e.g. PrismaClientKnownRequestError). |
ExternalErrFactory<C>
An ExternalErrFactory callable as a constructor and usable
in matchErr .on().
import { PrismaClientKnownRequestError } from "@prisma/client";
const PrismaErr = wrapError(PrismaClientKnownRequestError);
matchErr(result)
.on(PrismaErr, (e) => `Prisma error ${e.code}`)
.otherwise((e) => `Other: ${e.message}`);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.
| Parameter | Type | Description |
|---|---|---|
message |
string |
The error message. |
options? |
ReportOptions<Record<string, unknown>> |
Additional report options. |
A new Report instance.
return Err(bail("Permission denied", { help: "Check your API token" }));function Err<T, E>(error): Result<T, E>;Defined in: factories/err.ts:17
Constructs an error Result containing the given error.
| Type Parameter | Description |
|---|---|
T |
The type of the success value. |
E |
The type of the error value. |
| Parameter | Type | Description |
|---|---|---|
error |
E |
The error to wrap in an Err result. |
Result<T, E>
A failed Result object { ok: false, error: E }.
Ok
const res = Err("Something went wrong");
if (!res.ok) console.error(res.error); // "Something went wrong"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 Parameter | Description |
|---|---|
T |
The type of the success value. |
E |
The type of the error value. |
| Parameter | Type | Description |
|---|---|---|
result |
Result<T, E> |
The Result to check. |
result is { error: E; ok: false }
true if the result is an Err, false otherwise.
if (isErr(res)) {
console.error(res.error); // res.error is typed as E
}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 Parameter | Description |
|---|---|
T |
The type of the success value. |
E |
The type of the error value. |
| Parameter | Type | Description |
|---|---|---|
result |
Result<T, E> |
The Result to check. |
result is { ok: true; value: T }
true if the result is an Ok, false otherwise.
if (isOk(res)) {
console.log(res.value); // res.value is typed as T
}function Ok<T, E>(...args): Result<T, E>;Defined in: factories/ok.ts:17
Constructs a successful Result containing the given value.
| Type Parameter | Default type | Description |
|---|---|---|
T |
void |
The type of the success value. |
E |
unknown |
The type of the error value. |
| Parameter | Type | Description |
|---|---|---|
...args
|
undefined extends T ? [T?] : [T] |
The value to wrap in an Ok result. Required if T is not void. |
Result<T, E>
A successful Result object { ok: true, value: T }.
Err
const res = Ok(42);
if (res.ok) console.log(res.value); // 42function 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 Parameter | Default type | Description |
|---|---|---|
T |
- | The type of the success value. |
E |
Error |
The type of the error value. Defaults to Error. |
| Parameter | Type | Description |
|---|---|---|
fn |
() => T
|
The function to execute. |
Result<T, E>
An Ok result with the return value, or an Err result with the thrown error.
safeAsync
const res = safe(() => JSON.parse('{"valid": true}'));
if (res.ok) console.log(res.value);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 Parameter | Default type | Description |
|---|---|---|
T |
- | The type of the success value. |
E |
Error |
The type of the error value. Defaults to Error. |
| Parameter | Type | Description |
|---|---|---|
promise |
Promise<T> |
The Promise to convert. |
Promise<Result<T, E>>
A Promise resolving to an Ok result with the data, or an Err result with the error.
safe
const res = await safeAsync(fetch("https://api.example.com"));
if (res.ok) console.log(await res.value.json());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 Parameter | Description |
|---|---|
T |
The type of the success value. |
E |
The type of the error value. |
R |
The type of the new success value. |
| 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. |
Result<R, E>
A new Result representing the chained operation.
map
const res = Ok("user_id");
const user = andThen(res, fetchUser); // fetchUser returns a Resultfunction 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 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. |
| 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). |
A Result with the same success value or a Report as the error.
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.
const res = context(safe(() => JSON.parse(data)), "Failed to parse config");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 Parameter | Description |
|---|---|
T |
The type of the success value. |
E |
The type of the error value. |
R |
The type of the new success value. |
| 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. |
Result<R, E>
A new Result with the mapped success value or the original error.
- mapErr
- andThen
const res = Ok(1);
const doubled = map(res, (n) => n * 2); // Ok(2)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 Parameter | Description |
|---|---|
T |
The type of the success value. |
E |
The type of the error value. |
F |
The type of the new error value. |
| 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. |
Result<T, F>
A new Result with the mapped error value or the original success.
- map
- orElse
const res = Err("not found");
const wrapped = mapErr(res, (e) => new Error(e)); // Err(Error("not found"))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 Parameter | Description |
|---|---|
T |
The type of the success value. |
E |
The type of the error value. |
| Parameter | Type | Description |
|---|---|---|
result |
Result<T, E> |
The Result to attach a note to. |
msg |
string |
The note message to append. |
Result<T, Report<Record<string, unknown>>>
A Result with the same success value or a Report with the appended note.
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"]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 Parameter | Description |
|---|---|
T |
The type of the success value. |
E |
The type of the error value. |
F |
The type of the new error value. |
| 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. |
Result<T, F>
A new Result representing the chained operation with potential recovery.
mapErr
const res = Err("failed");
const recovered = orElse(res, () => Ok("default")); // Ok("default")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 Parameter | Description |
|---|---|
T |
The type of the success value. |
E |
The type of the error value. |
| Parameter | Type | Description |
|---|---|---|
result |
Result<T, E> |
The Result to tap into. |
fn |
(value) => void
|
The function to execute with the success value. |
Result<T, E>
The original Result unchanged.
tapErr
map(res, val => val + 1).tap(val => console.log(val))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 Parameter | Description |
|---|---|
T |
The type of the success value. |
E |
The type of the error value. |
| Parameter | Type | Description |
|---|---|---|
result |
Result<T, E> |
The Result to tap into. |
fn |
(error) => void
|
The function to execute with the error value. |
Result<T, E>
The original Result unchanged.
tap
safe(() => doSomething()).tapErr(err => logger.error(err))type AsyncResult<T, E> = Promise<Result<T, E>>;Defined in: types/result.ts:15
Represents a Result that is asynchronously resolved.
| Type Parameter | Description |
|---|---|
T |
The type of the success value. |
E |
The type of the error value. |
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 Parameter | Description |
|---|---|
T |
The type of the success value. |
E |
The type of the error value. |
function createReport<C>(message, options?): Report<C>;Defined in: report.ts:49
Creates a new Report instance.
| Type Parameter | Default type |
|---|---|
C extends Record<string, unknown> |
Record<string, unknown> |
| Parameter | Type | Description |
|---|---|---|
message |
string |
The error message. |
options |
ReportOptions<C> |
Additional options for the report. |
Report<C>
A new Report object.
function isReport(err): err is Report<Record<string, unknown>>;Defined in: report.ts:79
Checks if a value is a Report.
| Parameter | Type | Description |
|---|---|---|
err |
unknown |
The value to check. |
err is Report<Record<string, unknown>>
True if the value is a Report.
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 Parameter | Default type |
|---|---|
T extends Record<string, unknown> |
Record<string, unknown> |
| Parameter | Type | Description |
|---|---|---|
err |
unknown |
The original error. |
message? |
string |
An optional new message. |
options? |
ReportOptions<T> |
Additional options. |
Report<T>
A Report instance.
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 Parameter | Description |
|---|---|
T extends readonly Result<unknown, unknown>[] |
The type of the input Results array. |
| Parameter | Type | Description |
|---|---|---|
results |
[...T[]] |
An array of Results to combine. |
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.
any
const res = all([Ok(1), Ok("a")]); // Result<[number, string], 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 Parameter | Description |
|---|---|
T |
The type of the success value. |
E |
The type of the error value. |
| Parameter | Type | Description |
|---|---|---|
results |
Result<T, E>[] |
An array of Results to check. |
Result<T, E>
The first Ok result or the last Err.
all
const res = any([Err("a"), Ok(1), Ok(2)]); // Ok(1)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).
| Parameter | Type | Description |
|---|---|---|
err |
unknown |
The error to extract the kind from. |
string | undefined
The error kind string, or undefined if not found.
const kind = kindOf(err);
if (kind === "userNotFound") { ... }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 Parameter |
|---|
T |
| Parameter | Type |
|---|---|
value |
T | Promise<T> |
Promise<Awaited<T>>
const result = await pipe(
safe(() => JSON.parse(input)),
(r) => map(r, (data: any) => data.a),
(r) => unwrapOr(r, 0),
);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 Parameter |
|---|
T |
F1 |
| Parameter | Type |
|---|---|
value |
T | Promise<T> |
f1 |
(arg) => F1
|
Promise<Awaited<F1>>
const result = await pipe(
safe(() => JSON.parse(input)),
(r) => map(r, (data: any) => data.a),
(r) => unwrapOr(r, 0),
);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 Parameter |
|---|
T |
F1 |
F2 |
| Parameter | Type |
|---|---|
value |
T | Promise<T> |
f1 |
(arg) => F1
|
f2 |
(arg) => F2
|
Promise<Awaited<F2>>
const result = await pipe(
safe(() => JSON.parse(input)),
(r) => map(r, (data: any) => data.a),
(r) => unwrapOr(r, 0),
);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 Parameter |
|---|
T |
F1 |
F2 |
F3 |
| Parameter | Type |
|---|---|
value |
T | Promise<T> |
f1 |
(arg) => F1
|
f2 |
(arg) => F2
|
f3 |
(arg) => F3
|
Promise<Awaited<F3>>
const result = await pipe(
safe(() => JSON.parse(input)),
(r) => map(r, (data: any) => data.a),
(r) => unwrapOr(r, 0),
);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 Parameter |
|---|
T |
F1 |
F2 |
F3 |
F4 |
| Parameter | Type |
|---|---|
value |
T | Promise<T> |
f1 |
(arg) => F1
|
f2 |
(arg) => F2
|
f3 |
(arg) => F3
|
f4 |
(arg) => F4
|
Promise<Awaited<F4>>
const result = await pipe(
safe(() => JSON.parse(input)),
(r) => map(r, (data: any) => data.a),
(r) => unwrapOr(r, 0),
);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 Parameter |
|---|
T |
F1 |
F2 |
F3 |
F4 |
F5 |
| Parameter | Type |
|---|---|
value |
T | Promise<T> |
f1 |
(arg) => F1
|
f2 |
(arg) => F2
|
f3 |
(arg) => F3
|
f4 |
(arg) => F4
|
f5 |
(arg) => F5
|
Promise<Awaited<F5>>
const result = await pipe(
safe(() => JSON.parse(input)),
(r) => map(r, (data: any) => data.a),
(r) => unwrapOr(r, 0),
);