Skip to content

unthrown


unthrown

Classes

UnwrapError

Defined in: packages/core/src/core.ts:29

Thrown by a Result's unwrap / unwrapErr when the assertion is wrong on a modeled result — unwrap() on an Err, or unwrapErr() on an Ok.

Remarks

A Defect is never wrapped in an UnwrapError: its original cause is re-thrown (with its original stack) instead.

Extends

  • Error

Type Parameters

Type ParameterDefault typeDescription
Eunknownthe type of the UnwrapError.error it carries.

Constructors

Constructor
ts
new UnwrapError<E>(error): UnwrapError<E>;

Defined in: packages/core/src/core.ts:35

Parameters
ParameterType
errorE
Returns

UnwrapError<E>

Overrides
ts
Error.constructor

Properties

PropertyModifierTypeDescriptionInherited fromDefined in
cause?publicunknown-Error.causenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es2022.error.d.ts:24
errorreadonlyEThe offending value: the Err error for unwrap(), or the Ok value for unwrapErr().-packages/core/src/core.ts:34
messagepublicstring-Error.messagenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1075
namepublicstring-Error.namenode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1074
stack?publicstring-Error.stacknode_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1076
stackTraceLimitstaticnumberThe Error.stackTraceLimit property specifies the number of stack frames collected by a stack trace (whether generated by new Error().stack or Error.captureStackTrace(obj)). The default value is 10 but may be set to any valid JavaScript number. Changes will affect any stack trace captured after the value has been changed. If set to a non-number value, or set to a negative number, stack traces will not capture any frames.Error.stackTraceLimitnode_modules/.pnpm/@types+node@24.13.2/node_modules/@types/node/globals.d.ts:68

Methods

captureStackTrace()
ts
static captureStackTrace(targetObject, constructorOpt?): void;

Defined in: node_modules/.pnpm/@types+node@24.13.2/node_modules/@types/node/globals.d.ts:52

Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.

js
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack;  // Similar to `new Error().stack`

The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.

The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.

The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:

js
function a() {
  b();
}

function b() {
  c();
}

function c() {
  // Create an error without stack trace to avoid calculating the stack trace twice.
  const { stackTraceLimit } = Error;
  Error.stackTraceLimit = 0;
  const error = new Error();
  Error.stackTraceLimit = stackTraceLimit;

  // Capture the stack trace above function b
  Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
  throw error;
}

a();
Parameters
ParameterType
targetObjectobject
constructorOpt?Function
Returns

void

Inherited from
ts
Error.captureStackTrace
prepareStackTrace()
ts
static prepareStackTrace(err, stackTraces): any;

Defined in: node_modules/.pnpm/@types+node@24.13.2/node_modules/@types/node/globals.d.ts:56

Parameters
ParameterType
errError
stackTracesCallSite[]
Returns

any

See

https://v8.dev/docs/stack-trace-api#customizing-stack-traces

Inherited from
ts
Error.prepareStackTrace

Type Aliases

AsyncResult

ts
type AsyncResult<T, E> = Awaitable<Result<T, E>> & object;

Defined in: packages/core/src/types.ts:278

The asynchronous counterpart of Result: an awaitable wrapper with the same method surface, collapsing to a Result<T, E> when await-ed.

Type Declaration

NameTypeDescriptionDefined in
as()(value) => AsyncResult<U, E>Asynchronous as.packages/core/src/types.ts:289
flatMap()(f) => AsyncResult<U, E | E2>Asynchronous flatMap. f may return a Result or an AsyncResult (never a raw Promise); a throw becomes a Defect.packages/core/src/types.ts:285
getOrNull()() => Promise<T | null>Asynchronous getOrNull.packages/core/src/types.ts:322
getOrUndefined()() => Promise<T | undefined>Asynchronous getOrUndefined.packages/core/src/types.ts:324
map()(f) => AsyncResult<U, E>Asynchronous map. f is synchronous; a throw becomes a Defect.packages/core/src/types.ts:280
mapErr()(f) => AsyncResult<T, E2>Asynchronous mapErr. f is synchronous; a throw becomes a Defect.packages/core/src/types.ts:292
match()(cases) => Promise<R>Asynchronous match. Handlers are synchronous; resolves to R.packages/core/src/types.ts:308
orElse()(f) => AsyncResult<T | U, E2>Asynchronous orElse. f may return a Result or an AsyncResult.packages/core/src/types.ts:294
recover()(f) => AsyncResult<T | U, never>Asynchronous recover. f is synchronous; a throw becomes a Defect.packages/core/src/types.ts:296
recoverDefect()(f) => AsyncResult<T | U, E | E2>Asynchronous recoverDefect. f may return a Result or an AsyncResult.packages/core/src/types.ts:301
tap()(f) => AsyncResult<T, E>Asynchronous tap. f is synchronous; a throw becomes a Defect.packages/core/src/types.ts:287
tapDefect()(f) => AsyncResult<T, E>Asynchronous tapDefect.packages/core/src/types.ts:305
tapErr()(f) => AsyncResult<T, E>Asynchronous tapErr. f is synchronous; a throw becomes a Defect.packages/core/src/types.ts:298
unwrap()() => Promise<T>Asynchronous unwrap. The returned promise rejects on Err/Defect.packages/core/src/types.ts:314
unwrapErr()() => Promise<E>Asynchronous unwrapErr.packages/core/src/types.ts:316
unwrapOr()(fallback) => Promise<T>Asynchronous unwrapOr.packages/core/src/types.ts:318
unwrapOrElse()(f) => Promise<T>Asynchronous unwrapOrElse.packages/core/src/types.ts:320

Type Parameters

Type ParameterDescription
Tthe success value type.
Ethe modeled error type.

Remarks

Combinator callbacks are synchronous. A raw Promise may never enter an AsyncResult method — that would be an un-qualified async boundary, and its rejection would silently become a Defect, skipping the triage that fromPromise forces. To do further async work, re-enter through a qualified boundary and compose it: ar.flatMap((v) => fromPromise(work(v), qualify)). The eliminators (unwrap, …) return promises; the binds (flatMap, orElse, recoverDefect) additionally accept an AsyncResult.

To pattern-match an AsyncResult, await it first: match(await ar).


Awaitable

ts
type Awaitable<T> = object;

Defined in: packages/core/src/types.ts:256

A success-only thenable: awaitable, but deliberately not a full PromiseLike.

Remarks

An AsyncResult's internal promise never rejects, so await-ing one always yields a Result and never throws — there is no rejection channel to model, and none is advertised. At runtime it is still a thenable (the only way await can collapse it); the narrowing simply keeps it from being treated as a raw promise (e.g. dropped into Promise.all).

Type Parameters

Type ParameterDescription
Tthe value await resolves to.

Methods

then()
ts
then<R>(onfulfilled?): PromiseLike<R>;

Defined in: packages/core/src/types.ts:257

Type Parameters
Type ParameterDefault type
RT
Parameters
ParameterType
onfulfilled?((value) => R | PromiseLike<R>) | null
Returns

PromiseLike<R>


Defect

ts
type Defect = object;

Defined in: packages/core/src/defect.ts:15

The marker a qualify function returns to triage a cause as unexpected.

Remarks

qualify (passed to fromPromise / fromThrowable) returns E | Defect: either a modeled domain error, or a Defect produced by defect to say "this failure is not modeled". A Defect is opaque — it carries the original cause for the boundary to convert into the third runtime state of a Result.

Properties

PropertyModifierTypeDefined in
[DEFECT]readonlytruepackages/core/src/defect.ts:16
causereadonlyunknownpackages/core/src/defect.ts:17

DefectView

ts
type DefectView<T, E> = ResultMethods<T, E> & object;

Defined in: packages/core/src/types.ts:199

The Defect variant of a Result: an unmodeled failure carrying a cause.

Type Declaration

NameTypeDefined in
causeunknownpackages/core/src/types.ts:201
tag"Defect"packages/core/src/types.ts:200

Type Parameters

Type ParameterDefault type
Tnever
Enever

ErrOf

ts
type ErrOf<R> = R extends object ? E : never;

Defined in: packages/core/src/types.ts:338

Extract the error type E from a Result.

Type Parameters

Type ParameterDescription
Rthe Result type to inspect.

ErrView

ts
type ErrView<E, T> = ResultMethods<T, E> & object;

Defined in: packages/core/src/types.ts:194

The Err variant of a Result: a modeled failure carrying an error.

Type Declaration

NameTypeDefined in
errorEpackages/core/src/types.ts:196
tag"Err"packages/core/src/types.ts:195

Type Parameters

Type ParameterDefault type
E-
Tnever

OkOf

ts
type OkOf<R> = R extends object ? T : never;

Defined in: packages/core/src/types.ts:332

Extract the success type T from a Result.

Type Parameters

Type ParameterDescription
Rthe Result type to inspect.

OkView

ts
type OkView<T, E> = ResultMethods<T, E> & object;

Defined in: packages/core/src/types.ts:189

The Ok variant of a Result: a success carrying a value.

Type Declaration

NameTypeDefined in
tag"Ok"packages/core/src/types.ts:190
valueTpackages/core/src/types.ts:191

Type Parameters

Type ParameterDefault type
T-
Enever

Result

ts
type Result<T, E> = ResultType<T, E>;

Defined in: packages/core/src/facade.ts:31

Companion object grouping the standalone entry points under a single, discoverable namespace: Result.ok, Result.err, Result.defect, Result.fromNullable, Result.fromThrowable, Result.fromPromise, Result.fromSafePromise, Result.all, Result.isOk, Result.isErr, Result.isDefect.

Type Parameters

Type Parameter
T
E

Remarks

Purely additive sugar — each member is the corresponding free function. The free functions remain the primary, tree-shakeable API; importing only { ok } never pulls this object in. The value Result and the type Result share one name (the companion-object pattern).

Example

ts
import { Result } from "unthrown";
Result.ok(1).flatMap((n) => Result.ok(n + 1)).unwrap(); // 2

TaggedErrorConstructor

ts
type TaggedErrorConstructor<Tag> = <A>(args) => TaggedErrorInstance<Tag, A>;

Defined in: packages/core/src/tagged.ts:28

The class constructor returned by TaggedError. Generic in its payload: apply it with an instantiation expression at the extends site.

Type Parameters

Type ParameterDescription
Tag extends stringthe string literal discriminant.

Parameters

ParameterType
argskeyof A extends never ? void : A

Returns

TaggedErrorInstance<Tag, A>

Remarks

When the payload is empty, the constructor takes no arguments (the keyof A extends never ? void : A trick); otherwise it takes the payload.


TaggedErrorInstance

ts
type TaggedErrorInstance<Tag, A> = Error & Readonly<A> & object;

Defined in: packages/core/src/tagged.ts:15

The instance shape produced by a TaggedError class: an Error plus a _tag discriminant and the (readonly) payload fields.

Type Declaration

NameTypeDefined in
_tagTagpackages/core/src/tagged.ts:16

Type Parameters

Type ParameterDescription
Tag extends stringthe string literal discriminant.
A extends Propsthe payload object type.

TagHandlers

ts
type TagHandlers<T, E, R> = object & { [K in E["_tag"]]: (error: Extract<E, { _tag: K }>) => R };

Defined in: packages/core/src/tagged.ts:81

The handler object matchTags requires: a branch per error tag, plus Ok and Defect. Miss a tag and it will not compile — the exhaustiveness is enforced by the type, with no .exhaustive() to forget.

Type Declaration

NameTypeDefined in
Defect()(cause) => Rpackages/core/src/tagged.ts:83
Ok()(value) => Rpackages/core/src/tagged.ts:82

Type Parameters

Type ParameterDescription
Tthe success value type.
E extends objectthe tagged error union.
Rthe folded result type.

Variables

Result

ts
const Result: object;

Defined in: packages/core/src/facade.ts:31

Companion object grouping the standalone entry points under a single, discoverable namespace: Result.ok, Result.err, Result.defect, Result.fromNullable, Result.fromThrowable, Result.fromPromise, Result.fromSafePromise, Result.all, Result.isOk, Result.isErr, Result.isDefect.

Type Declaration

NameTypeDefined in
all()<Rs>(results) => Result<{ [K in string | number | symbol]: OkOf<Rs[K]> }, ErrOf<Rs[number]>>packages/core/src/facade.ts:39
defect()(cause) => Defectpackages/core/src/facade.ts:34
err()<E>(error) => Result<never, E>packages/core/src/facade.ts:33
fromNullable()<T, E>(value, onAbsent) => Result<NonNullable<T>, E>packages/core/src/facade.ts:35
fromPromise()<T, E>(promise, qualify) => AsyncResult<T, E>packages/core/src/facade.ts:37
fromSafePromise()<T>(promise) => AsyncResult<T, never>packages/core/src/facade.ts:38
fromThrowable()<A, T, E>(fn, qualify) => (...args) => Result<T, E>packages/core/src/facade.ts:36
isDefect()<T, E>(r) => r is DefectView<T, E>packages/core/src/facade.ts:42
isErr()<T, E>(r) => r is ErrView<E, T>packages/core/src/facade.ts:41
isOk()<T, E>(r) => r is OkView<T, E>packages/core/src/facade.ts:40
ok()<T>(value) => Result<T, never>packages/core/src/facade.ts:32

Remarks

Purely additive sugar — each member is the corresponding free function. The free functions remain the primary, tree-shakeable API; importing only { ok } never pulls this object in. The value Result and the type Result share one name (the companion-object pattern).

Example

ts
import { Result } from "unthrown";
Result.ok(1).flatMap((n) => Result.ok(n + 1)).unwrap(); // 2

Functions

all()

ts
function all<Rs>(results): Result<{ [K in string | number | symbol]: OkOf<Rs[K]> }, ErrOf<Rs[number]>>;

Defined in: packages/core/src/interop.ts:162

Collect a tuple of Results into a single Result of the tuple of success values.

Type Parameters

Type ParameterDescription
Rs extends readonly Result<unknown, unknown>[]the tuple of input Result types.

Parameters

ParameterTypeDescription
resultsreadonly [Rs]the results to combine.

Returns

Result<{ [K in string | number | symbol]: OkOf<Rs[K]> }, ErrOf<Rs[number]>>

Remarks

Short-circuits on the first Err (later entries are not inspected for their error); any Defect present dominates, winning even over an earlier Err. Positional types are preserved, so all([ok(1), ok("a")]) is Result<[number, string], …>.

Example

ts
import { all, ok } from "unthrown";
all([ok(1), ok("a"), ok(true)]).unwrap(); // [1, "a", true]

defect()

ts
function defect(cause): Defect;

Defined in: packages/core/src/defect.ts:36

Wrap a cause as a Defect — the value you return from a qualify function when a failure is not a modeled domain error.

Parameters

ParameterTypeDescription
causeunknownthe original thrown/rejected value.

Returns

Defect

an opaque defect marker carrying cause.

Example

ts
import { fromPromise, defect } from "unthrown";

const user = fromPromise(fetchUser(id), (cause) =>
  cause instanceof NotFoundError ? cause : defect(cause),
);

err()

ts
function err<E>(error): Result<never, E>;

Defined in: packages/core/src/constructors.ts:34

Construct a failed Result carrying a modeled error.

Type Parameters

Type ParameterDescription
Ethe modeled error type.

Parameters

ParameterTypeDescription
errorEthe domain error to wrap.

Returns

Result<never, E>

Example

ts
import { err } from "unthrown";
err("not_found").unwrapErr(); // "not_found"

fromNullable()

ts
function fromNullable<T, E>(value, onAbsent): Result<NonNullable<T>, E>;

Defined in: packages/core/src/interop.ts:29

Bridge a nullable value into a Result: absence becomes a modeledErr. The sanctioned alternative to an Option type.

Type Parameters

Type ParameterDescription
Tthe (nullable) value type.
Ethe error produced when the value is absent.

Parameters

ParameterTypeDescription
valueT | null | undefinedthe possibly-absent value.
onAbsent() => Elazily produces the error for the absent case.

Returns

Result<NonNullable<T>, E>

Remarks

null and undefined map to err(onAbsent()); any other value (including falsy ones like 0, "", false) maps to Ok.

Example

ts
import { fromNullable } from "unthrown";
fromNullable(map.get(key), () => "missing").unwrap();

fromPromise()

ts
function fromPromise<T, E>(promise, qualify): AsyncResult<T, E>;

Defined in: packages/core/src/interop.ts:95

Wrap a Promise (or a thunk producing one) as an AsyncResult, forcing every rejection to be triaged.

Type Parameters

Type ParameterDescription
Tthe resolved value type.
Ethe modeled error type.

Parameters

ParameterTypeDescription
promisePromise<T> | (() => Promise<T>)the promise, or a thunk returning one.
qualify(cause) => Defect | Etriages a rejection cause into E or a Defect.

Returns

AsyncResult<T, E>

Remarks

qualify must map each rejection cause into a modeled error E or a Defect. The returned AsyncResult's internal promise never rejects; await-ing it always yields a Result. A throw inside qualify is itself a Defect.

Example

ts
import { fromPromise, defect } from "unthrown";
const user = await fromPromise(fetchUser(id), (cause) =>
  cause instanceof NotFoundError ? ("not_found" as const) : defect(cause),
);

fromSafePromise()

ts
function fromSafePromise<T>(promise): AsyncResult<T, never>;

Defined in: packages/core/src/interop.ts:119

Wrap a Promise asserted not to fail in any modeled way: any rejection becomes a Defect.

Type Parameters

Type ParameterDescription
Tthe resolved value type.

Parameters

ParameterTypeDescription
promisePromise<T> | (() => Promise<T>)the promise, or a thunk returning one.

Returns

AsyncResult<T, never>

Remarks

Use this only when a rejection genuinely indicates a bug rather than an anticipated outcome — the error channel is never, so there is nothing to triage. (await-ing still yields a Result; it never throws.)


fromThrowable()

ts
function fromThrowable<A, T, E>(fn, qualify): (...args) => Result<T, E>;

Defined in: packages/core/src/interop.ts:59

Wrap a throwing synchronous function so it returns a Result instead of throwing.

Type Parameters

Type ParameterDescription
A extends unknown[]the wrapped function's argument tuple.
Tthe wrapped function's return type.
Ethe modeled error type.

Parameters

ParameterTypeDescription
fn(...args) => Tthe throwing function to wrap.
qualify(cause) => Defect | Etriages a thrown cause into E or a Defect.

Returns

a function with the same arguments returning Result<T, E>.

(...args) => Result<T, E>

Remarks

qualify must triage every thrown cause into a modeled error E or a Defect (via defect) — there is no path that leaves unknown in E. A throw inside qualify itself is treated as a Defect.

Example

ts
import { fromThrowable, defect } from "unthrown";
const parse = fromThrowable(JSON.parse, (cause) => defect(cause));
parse("{}").unwrap();

isDefect()

ts
function isDefect<T, E>(r): r is DefectView<T, E>;

Defined in: packages/core/src/constructors.ts:66

Type guard: narrow a Result to its Defect variant, exposing .cause.

Type Parameters

Type Parameter
T
E

Parameters

ParameterType
rResult<T, E>

Returns

r is DefectView<T, E>

true when r is a Defect.


isErr()

ts
function isErr<T, E>(r): r is ErrView<E, T>;

Defined in: packages/core/src/constructors.ts:58

Type guard: narrow a Result to its Err variant, exposing .error.

Type Parameters

Type Parameter
T
E

Parameters

ParameterType
rResult<T, E>

Returns

r is ErrView<E, T>

true when r is Err.


isOk()

ts
function isOk<T, E>(r): r is OkView<T, E>;

Defined in: packages/core/src/constructors.ts:50

Type guard: narrow a Result to its Ok variant, exposing .value.

Type Parameters

Type Parameter
T
E

Parameters

ParameterType
rResult<T, E>

Returns

r is OkView<T, E>

true when r is Ok.

Example

ts
import { isOk, type Result } from "unthrown";
declare const r: Result<number, string>;
if (isOk(r)) r.value; // number, narrowed

matchTags()

Call Signature

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

Defined in: packages/core/src/tagged.ts:116

Exhaustively fold a Result (or AsyncResult) whose error type is a tagged union, dispatching each error to the handler matching its _tag.

Type Parameters
Type ParameterDescription
Tthe success value type.
E extends objectthe tagged error union (E extends { _tag: string }).
Rthe folded result type.
Parameters
ParameterTypeDescription
resultResult<T, E>the result to fold.
handlersTagHandlers<T, E, R>one branch per channel/tag.
Returns

R

Remarks

The handlers object must provide Ok, Defect, and exactly one function per error tag; each tag's handler receives the narrowed error variant. A missing tag is a compile error. For an AsyncResult, the fold resolves to a Promise<R>.

Example
ts
class NotFound extends TaggedError("NotFound") {}
class Forbidden extends TaggedError("Forbidden")<{ user: string }> {}

declare const r: Result<number, NotFound | Forbidden>;
matchTags(r, {
  Ok: (n) => `got ${n}`,
  Defect: (cause) => `bug: ${String(cause)}`,
  NotFound: () => "404",
  Forbidden: (e) => `403 for ${e.user}`,
});

Call Signature

ts
function matchTags<T, E, R>(result, handlers): Promise<R>;

Defined in: packages/core/src/tagged.ts:120

Exhaustively fold a Result (or AsyncResult) whose error type is a tagged union, dispatching each error to the handler matching its _tag.

Type Parameters
Type ParameterDescription
Tthe success value type.
E extends objectthe tagged error union (E extends { _tag: string }).
Rthe folded result type.
Parameters
ParameterTypeDescription
resultAsyncResult<T, E>the result to fold.
handlersTagHandlers<T, E, R>one branch per channel/tag.
Returns

Promise<R>

Remarks

The handlers object must provide Ok, Defect, and exactly one function per error tag; each tag's handler receives the narrowed error variant. A missing tag is a compile error. For an AsyncResult, the fold resolves to a Promise<R>.

Example
ts
class NotFound extends TaggedError("NotFound") {}
class Forbidden extends TaggedError("Forbidden")<{ user: string }> {}

declare const r: Result<number, NotFound | Forbidden>;
matchTags(r, {
  Ok: (n) => `got ${n}`,
  Defect: (cause) => `bug: ${String(cause)}`,
  NotFound: () => "404",
  Forbidden: (e) => `403 for ${e.user}`,
});

ok()

ts
function ok<T>(value): Result<T, never>;

Defined in: packages/core/src/constructors.ts:18

Construct a successful Result.

Type Parameters

Type ParameterDescription
Tthe success value type.

Parameters

ParameterTypeDescription
valueTthe success value to wrap.

Returns

Result<T, never>

Example

ts
import { ok } from "unthrown";
ok(42).unwrap(); // 42

TaggedError()

ts
function TaggedError<Tag>(tag): TaggedErrorConstructor<Tag>;

Defined in: packages/core/src/tagged.ts:54

Build a base class for a tagged error — a class extending Error with a _tag string discriminant, in the style of Effect's Data.TaggedError.

Type Parameters

Type ParameterDescription
Tag extends stringthe string literal discriminant.

Parameters

ParameterTypeDescription
tagTagthe discriminant value, also used as the error name.

Returns

TaggedErrorConstructor<Tag>

Remarks

Extend the returned class to declare a concrete error. Supply the payload with an instantiation expression; omit it for a payload-less error. A message field in the payload is forwarded to Error. The _tag always reflects tag and cannot be overridden by the payload.

Example

ts
class NotFound extends TaggedError("NotFound") {}
class HttpError extends TaggedError("HttpError")<{ status: number }> {}

new NotFound()._tag; // "NotFound"
new HttpError({ status: 500 }).status; // 500

Released under the MIT License.