@zerothrow/core
Version:
Core ZeroThrow functionality - Rust-style Result<T,E> for TypeScript
96 lines (93 loc) • 2.89 kB
text/typescript
type ErrorCode = string | number | symbol;
interface ErrorContext {
[k: string]: unknown;
}
/**
* ZeroError wraps a standard JS Error but adds:
* - code : machine‑readable categorisation
* - context : structured payload for logging
* - cause : native Error.cause chain (ES2022)
*/
declare class ZeroError<C extends ErrorContext = ErrorContext> extends Error {
readonly code: ErrorCode;
readonly context?: C;
constructor(code: ErrorCode, message: string, opts?: {
cause?: Error;
context?: C;
});
/**
* Override toString to include full error chain with context
*/
toString(): string;
/**
* Get the full stack trace including all causes
*/
getFullStack(): string;
}
type Ok<T> = {
ok: true;
value: T;
};
type Err<E extends Error = ZeroError> = {
ok: false;
error: E;
};
type Result<T, E extends Error = ZeroError> = (Ok<T> | Err<E>) & ResultMethods<T, E>;
/**
* Result methods - every Result has these built-in
*/
interface ResultMethods<T, E extends Error = ZeroError> {
/**
* Chain operations that can fail
*/
andThen<U>(fn: (value: T) => Result<U, E>): Result<U, E>;
/**
* Transform errors while preserving success values
*/
mapErr<F extends Error>(fn: (error: E) => F): Result<T, F>;
/**
* Transform success values while preserving errors
*/
map<U>(fn: (value: T) => U): Result<U, E>;
/**
* Provide fallback value on error
*/
orElse(fallback: () => Result<T, E>): Result<T, E>;
/**
* Get value or fallback
*/
unwrapOr(fallback: T): T;
/**
* Get value or throw (use sparingly!)
*/
unwrapOrThrow(): T;
/**
* Execute side effect without changing the Result
*/
tap(fn: (value: T) => void): Result<T, E>;
/**
* Execute side effect on error without changing the Result
*/
tapErr(fn: (error: E) => void): Result<T, E>;
/**
* Execute side effect on any result
*/
finally(fn: (value?: T) => void): Result<T, E>;
/**
* Discard the value and return void
*/
void(): Result<void, E>;
}
declare const ok: <T>(value: T) => Result<T, ZeroError>;
declare const err: <E extends Error>(error: E) => Result<never, E>;
/**
* Normalise an unknown thrown value into ZeroError
* Optimized to avoid creating new errors when possible
*/
declare const normalise: (e: unknown) => ZeroError;
/**
* wrap(cause, code?, msg?, ctx?) lifts an existing error into a new coded layer.
* If code/msg are not provided, they are extracted from the cause error.
*/
declare function wrap<C extends ErrorContext = ErrorContext>(cause: Error, code?: ErrorCode, msg?: string, ctx?: C): ZeroError<C>;
export { type Err, type ErrorCode, type ErrorContext, type Ok, type Result, type ResultMethods, ZeroError, err, normalise, ok, wrap };