Basic usage with static methods
Basic usage with static methods
import { Result } from "@qlever-llc/result"; function divide(a: number, b: number): Result<number, ValidationError> { if (b === 0) { return Result.err(new ValidationError("Division by zero")); } return Result.ok(a / b); } const result = divide(10, 2) .map(x => x * 2) .map(x => x + 1); const value = result.take(); if (Result.isErr(value)) return value; console.log(value); // 11
Async operations
Async operations
import { AsyncResult, Result } from "@qlever-llc/result"; const user = AsyncResult.try(async () => { const response = await fetch(`/api/users/123`); return await response.json(); }); const result = user .map(user => user.name) .map(name => name.toUpperCase()); const value = await result.take(); if (Result.isErr(value)) return value; console.log(value); // "ALICE"
An asynchronous Result class that represents a Promise of Result<T, E>.
-
all<T, E extends BaseError>(results: readonly (AsyncResult<T, E> | Promise<Result<T, E>>)[]): AsyncResult<T[], E>
Combines multiple AsyncResults into a single AsyncResult containing an array.
-
andThen<U, F extends BaseError>(fn: (value: T) => Result<U, F> | AsyncResult<U, F> | Promise<Result<U, F>>): AsyncResult<U, E | F>
Chains operations that return Results.
-
any<T, E extends BaseError>(results: readonly (AsyncResult<T, E> | Promise<Result<T, E>>)[]): AsyncResult<T, E>
Returns the first Ok result from an array of AsyncResults.
-
context(): AsyncResult<T, E>message: string,extra?: Record<string, unknown>
Adds context to an Err result for early returns. Async version - can be chained before take().
-
err<E extends BaseError, T = never>(error: E): AsyncResult<T, E>
Creates a failed AsyncResult with the given error.
-
from<T, E extends BaseError>(promise: Promise<Result<T, E>>): AsyncResult<T, E>
Creates an AsyncResult from a Promise of Result.
-
inspect(fn: (value: T) => void | Promise<void>): AsyncResult<T, E>
Performs a side effect on the Ok value without changing the result.
-
inspectErr(fn: (error: E) => void | Promise<void>): AsyncResult<T, E>
Performs a side effect on the Err value without changing the result.
-
lift<T, E extends BaseError>(value: Result<T, E> | AsyncResult<T, E> | Promise<Result<T, E>>): AsyncResult<T, E>
Creates an AsyncResult from a Result, AsyncResult, or Promise<Result>.
-
map<U>(fn: (value: T) => U): AsyncResult<U, E>
Transforms the Ok value using a mapper function, leaving Err untouched.
-
mapErr<F extends BaseError>(fn: (error: E) => F): AsyncResult<T, F>
Transforms the Err value using a mapper function, leaving Ok untouched.
-
match<U>(pattern: { ok: (value: T) => U; err: (error: E) => U; }): Promise<U>
Pattern matching for async Results.
-
ok<T, E extends BaseError = never>(value: T): AsyncResult<T, E>
Creates a successful AsyncResult with the given value.
-
or<U>(other: Result<U, E> | AsyncResult<U, E> | Promise<Result<U, E>>): AsyncResult<T | U, E>
Returns this result if Ok, otherwise returns the fallback.
-
orElse<U, F extends BaseError>(fn: (error: E) => Result<U, F> | AsyncResult<U, F> | Promise<Result<U, F>>): AsyncResult<T | U, F>
Returns this result if Ok, otherwise computes a fallback from the error.
-
orThrow(): Promise<T>
Returns the Ok value or throws the Err error.
-
take(): Promise<T | Result<never, E>>
Extracts the value from Ok or returns the Err for early returns.
-
then<TResult1 = Result<T, E>, TResult2 = never>(): Promise<TResult1 | TResult2>onfulfilled?:((value: Result<T, E>) => TResult1 | PromiseLike<TResult1>)
| null,onrejected?:((reason: unknown) => TResult2 | PromiseLike<TResult2>)
| nullImplements PromiseLike to make AsyncResult awaitable.
-
try<T>(): AsyncResult<T, UnexpectedError>fn: () => Promise<T>,context?: Record<string, unknown>
Wraps an async function that might throw into an AsyncResult.
-
unwrapOr<U>(defaultValue: U): Promise<T | U>
Returns the Ok value or a default value if Err.
-
unwrapOrElse<U>(fn: (error: E) => U): Promise<T | U>
Returns the Ok value or computes a default from the error.
Base class for all errors used in Result<T, E>.
-
baseSerializable(): BaseErrorSchema
Helper method to get base serializable fields. Subclasses should use this to build their complete serializable object.
-
getContext(): Record<string, unknown>
Get the current context object.
-
getTraceId(): string | undefined
Get the trace ID for this error. Returns the trace ID captured at error creation time.
-
id: string
Unique identifier for this error instance
-
name: string
Error type name (used for discrimination)
-
toJSON(): string
Serializes error to JSON string.
-
toSerializable(): TData
Serializes error to a plain object. Subclasses must implement this to return their specific data type.
-
traceIdGetter: (() => string | undefined) | undefined
Optional callback to provide a trace ID from ambient context (e.g. OpenTelemetry).
-
withContext(context?: Record<string, unknown>): this
Add contextual information to this error. Useful for adding runtime context like request IDs, user IDs, etc.
-
withTraceId(traceId: string | undefined): this
Attach a trace ID if one was not captured when the error was created.
A synchronous Result class that represents either success (Ok) or failure (Err).
-
_unsafeValue(): ResultValue<T, E>
Internal method to get the raw value (for testing/debugging). Not recommended for general use - prefer take() instead.
-
all<T, E extends BaseError>(results: readonly Result<T, E>[]): Result<T[], E>
Combines multiple Results into a single Result containing an array.
-
andThen<U, F extends BaseError>(fn: (value: T) => Result<U, F>): Result<U, E | F>
Chains operations that return Results (also known as flatMap).
-
any<T, E extends BaseError>(results: readonly Result<T, E>[]): Result<T, E>
Returns the first Ok result from an array of Results.
-
context(): Result<T, E>message: string,extra?: Record<string, unknown>
Adds context to an Err result for early returns. Chainable with take() for adding context when propagating errors.
-
err<E extends BaseError, T = never>(error: E): Result<T, E>
Creates a failed Result containing an error.
-
error(): E
Gets the error from an Err Result.
-
inspect(fn: (value: T) => void): Result<T, E>
Performs a side effect on the Ok value without changing the Result.
-
inspectErr(fn: (error: E) => void): Result<T, E>
Performs a side effect on the Err value without changing the Result.
-
isErr<T, E extends BaseError>(result: Result<T, E>): result is Result<never, E>
Type guard to check if a value is an Err Result.
-
isOk<T, E extends BaseError>(result: Result<T, E>): result is Result<T, never>
Type guard to check if a value is an Ok Result.
-
map<U>(fn: (value: T) => U): Result<U, E>
Transforms the Ok value using a mapper function, leaving Err untouched.
-
mapErr<F extends BaseError>(fn: (error: E) => F): Result<T, F>
Transforms the Err value using a mapper function, leaving Ok untouched.
-
match<U>(pattern: { ok: (value: T) => U; err: (error: E) => U; }): U
Pattern matching for Results - handle both Ok and Err cases.
-
ok<T, E extends BaseError = never>(value: T): Result<T, E>
Creates a successful Result containing a value.
-
or<U>(other: Result<U, E>): Result<T | U, E>
Returns this result if Ok, otherwise returns the fallback result.
-
orElse<U, F extends BaseError>(fn: (error: E) => Result<U, F>): Result<T | U, F>
Returns this result if Ok, otherwise computes a fallback from the error.
-
orThrow(): T
Returns the Ok value or throws the Err error.
-
take(): [T] extends [never] ? Result<never, E> : T | Result<never, E>
Extracts the value from Ok or returns the Err for early returns.
-
try<T>(): Result<T, UnexpectedError>fn: () => T,context?: Record<string, unknown>
Wraps a function that might throw into a Result.
-
unwrapOr<U>(defaultValue: U): T | U
Returns the Ok value or a default value if Err.
-
unwrapOrElse<U>(fn: (error: E) => U): T | U
Returns the Ok value or computes a default from the error.
Represents an unexpected error. Use this for wrapping unknown errors or for truly unexpected conditions.
- name: "UnexpectedError"
-
toSerializable(): UnexpectedErrorData
Serializes error to a plain object.
Extracts the Ok type T from a Result<T, E>.
Extracts the Err type E from a Result<T, E>.
A type that accepts either a Result or AsyncResult with the same T and E types.
Base error serialization schema. All errors serialize to this structure with optional additional fields.
Schema for UnexpectedError serialization.
Usage
import * as mod from "result/mod.ts";