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 Parameter | Default type | Description |
|---|---|---|
E | unknown | the type of the UnwrapError.error it carries. |
Constructors
Constructor
new UnwrapError<E>(error): UnwrapError<E>;Defined in: packages/core/src/core.ts:35
Parameters
| Parameter | Type |
|---|---|
error | E |
Returns
UnwrapError<E>
Overrides
Error.constructorProperties
| Property | Modifier | Type | Description | Inherited from | Defined in |
|---|---|---|---|---|---|
cause? | public | unknown | - | Error.cause | node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es2022.error.d.ts:24 |
error | readonly | E | The offending value: the Err error for unwrap(), or the Ok value for unwrapErr(). | - | packages/core/src/core.ts:34 |
message | public | string | - | Error.message | node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1075 |
name | public | string | - | Error.name | node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1074 |
stack? | public | string | - | Error.stack | node_modules/.pnpm/typescript@6.0.3/node_modules/typescript/lib/lib.es5.d.ts:1076 |
stackTraceLimit | static | number | The 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.stackTraceLimit | node_modules/.pnpm/@types+node@24.13.2/node_modules/@types/node/globals.d.ts:68 |
Methods
captureStackTrace()
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.
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:
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
| Parameter | Type |
|---|---|
targetObject | object |
constructorOpt? | Function |
Returns
void
Inherited from
Error.captureStackTraceprepareStackTrace()
static prepareStackTrace(err, stackTraces): any;Defined in: node_modules/.pnpm/@types+node@24.13.2/node_modules/@types/node/globals.d.ts:56
Parameters
| Parameter | Type |
|---|---|
err | Error |
stackTraces | CallSite[] |
Returns
any
See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Inherited from
Error.prepareStackTraceType Aliases
AsyncResult
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
| Name | Type | Description | Defined 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 Parameter | Description |
|---|---|
T | the success value type. |
E | the 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
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 Parameter | Description |
|---|---|
T | the value await resolves to. |
Methods
then()
then<R>(onfulfilled?): PromiseLike<R>;Defined in: packages/core/src/types.ts:257
Type Parameters
| Type Parameter | Default type |
|---|---|
R | T |
Parameters
| Parameter | Type |
|---|---|
onfulfilled? | ((value) => R | PromiseLike<R>) | null |
Returns
PromiseLike<R>
Defect
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
| Property | Modifier | Type | Defined in |
|---|---|---|---|
[DEFECT] | readonly | true | packages/core/src/defect.ts:16 |
cause | readonly | unknown | packages/core/src/defect.ts:17 |
DefectView
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
| Name | Type | Defined in |
|---|---|---|
cause | unknown | packages/core/src/types.ts:201 |
tag | "Defect" | packages/core/src/types.ts:200 |
Type Parameters
| Type Parameter | Default type |
|---|---|
T | never |
E | never |
ErrOf
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 Parameter | Description |
|---|---|
R | the Result type to inspect. |
ErrView
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
| Name | Type | Defined in |
|---|---|---|
error | E | packages/core/src/types.ts:196 |
tag | "Err" | packages/core/src/types.ts:195 |
Type Parameters
| Type Parameter | Default type |
|---|---|
E | - |
T | never |
OkOf
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 Parameter | Description |
|---|---|
R | the Result type to inspect. |
OkView
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
| Name | Type | Defined in |
|---|---|---|
tag | "Ok" | packages/core/src/types.ts:190 |
value | T | packages/core/src/types.ts:191 |
Type Parameters
| Type Parameter | Default type |
|---|---|
T | - |
E | never |
Result
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
import { Result } from "unthrown";
Result.ok(1).flatMap((n) => Result.ok(n + 1)).unwrap(); // 2TaggedErrorConstructor
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 Parameter | Description |
|---|---|
Tag extends string | the string literal discriminant. |
Parameters
| Parameter | Type |
|---|---|
args | keyof 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
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
| Name | Type | Defined in |
|---|---|---|
_tag | Tag | packages/core/src/tagged.ts:16 |
Type Parameters
| Type Parameter | Description |
|---|---|
Tag extends string | the string literal discriminant. |
A extends Props | the payload object type. |
TagHandlers
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
| Name | Type | Defined in |
|---|---|---|
Defect() | (cause) => R | packages/core/src/tagged.ts:83 |
Ok() | (value) => R | packages/core/src/tagged.ts:82 |
Type Parameters
| Type Parameter | Description |
|---|---|
T | the success value type. |
E extends object | the tagged error union. |
R | the folded result type. |
Variables
Result
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
| Name | Type | Defined in |
|---|---|---|
all() | <Rs>(results) => Result<{ [K in string | number | symbol]: OkOf<Rs[K]> }, ErrOf<Rs[number]>> | packages/core/src/facade.ts:39 |
defect() | (cause) => Defect | packages/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
import { Result } from "unthrown";
Result.ok(1).flatMap((n) => Result.ok(n + 1)).unwrap(); // 2Functions
all()
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 Parameter | Description |
|---|---|
Rs extends readonly Result<unknown, unknown>[] | the tuple of input Result types. |
Parameters
| Parameter | Type | Description |
|---|---|---|
results | readonly [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
import { all, ok } from "unthrown";
all([ok(1), ok("a"), ok(true)]).unwrap(); // [1, "a", true]defect()
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
| Parameter | Type | Description |
|---|---|---|
cause | unknown | the original thrown/rejected value. |
Returns
an opaque defect marker carrying cause.
Example
import { fromPromise, defect } from "unthrown";
const user = fromPromise(fetchUser(id), (cause) =>
cause instanceof NotFoundError ? cause : defect(cause),
);err()
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 Parameter | Description |
|---|---|
E | the modeled error type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
error | E | the domain error to wrap. |
Returns
Result<never, E>
Example
import { err } from "unthrown";
err("not_found").unwrapErr(); // "not_found"fromNullable()
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 Parameter | Description |
|---|---|
T | the (nullable) value type. |
E | the error produced when the value is absent. |
Parameters
| Parameter | Type | Description |
|---|---|---|
value | T | null | undefined | the possibly-absent value. |
onAbsent | () => E | lazily 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
import { fromNullable } from "unthrown";
fromNullable(map.get(key), () => "missing").unwrap();fromPromise()
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 Parameter | Description |
|---|---|
T | the resolved value type. |
E | the modeled error type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
promise | Promise<T> | (() => Promise<T>) | the promise, or a thunk returning one. |
qualify | (cause) => Defect | E | triages 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
import { fromPromise, defect } from "unthrown";
const user = await fromPromise(fetchUser(id), (cause) =>
cause instanceof NotFoundError ? ("not_found" as const) : defect(cause),
);fromSafePromise()
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 Parameter | Description |
|---|---|
T | the resolved value type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
promise | Promise<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()
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 Parameter | Description |
|---|---|
A extends unknown[] | the wrapped function's argument tuple. |
T | the wrapped function's return type. |
E | the modeled error type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
fn | (...args) => T | the throwing function to wrap. |
qualify | (cause) => Defect | E | triages 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
import { fromThrowable, defect } from "unthrown";
const parse = fromThrowable(JSON.parse, (cause) => defect(cause));
parse("{}").unwrap();isDefect()
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
| Parameter | Type |
|---|---|
r | Result<T, E> |
Returns
r is DefectView<T, E>
true when r is a Defect.
isErr()
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
| Parameter | Type |
|---|---|
r | Result<T, E> |
Returns
r is ErrView<E, T>
true when r is Err.
isOk()
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
| Parameter | Type |
|---|---|
r | Result<T, E> |
Returns
r is OkView<T, E>
true when r is Ok.
Example
import { isOk, type Result } from "unthrown";
declare const r: Result<number, string>;
if (isOk(r)) r.value; // number, narrowedmatchTags()
Call Signature
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 Parameter | Description |
|---|---|
T | the success value type. |
E extends object | the tagged error union (E extends { _tag: string }). |
R | the folded result type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
result | Result<T, E> | the result to fold. |
handlers | TagHandlers<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
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
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 Parameter | Description |
|---|---|
T | the success value type. |
E extends object | the tagged error union (E extends { _tag: string }). |
R | the folded result type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
result | AsyncResult<T, E> | the result to fold. |
handlers | TagHandlers<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
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()
function ok<T>(value): Result<T, never>;Defined in: packages/core/src/constructors.ts:18
Construct a successful Result.
Type Parameters
| Type Parameter | Description |
|---|---|
T | the success value type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
value | T | the success value to wrap. |
Returns
Result<T, never>
Example
import { ok } from "unthrown";
ok(42).unwrap(); // 42TaggedError()
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 Parameter | Description |
|---|---|
Tag extends string | the string literal discriminant. |
Parameters
| Parameter | Type | Description |
|---|---|---|
tag | Tag | the discriminant value, also used as the error name. |
Returns
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
class NotFound extends TaggedError("NotFound") {}
class HttpError extends TaggedError("HttpError")<{ status: number }> {}
new NotFound()._tag; // "NotFound"
new HttpError({ status: 500 }).status; // 500