Skip to content

Class: ResultFactory

Defined in: src/result.ts:1608

Methods

all()

static all<Items, Unwrapped>(...items): ListContainsAsync<Items> extends true ? AsyncResult<ExtractValues<Unwrapped>, ExtractErrors<Unwrapped>[number]> : Result<ExtractValues<Unwrapped>, ExtractErrors<Unwrapped>[number]>

Defined in: src/result.ts:1832

Similar to Promise.all, but for results. Useful when you want to run multiple independent operations and bundle the outcome into a single result. All possible values of the individual operations are collected into an array. Result.all will fail eagerly, meaning that as soon as any of the operations fail, the entire result will be a failure. Each argument can be a mixture of literal values, functions, Result or AsyncResult instances, or Promise.

Type Parameters

Items

Items extends any[]

Unwrapped

Unwrapped extends any[] = UnwrapList<Items>

Parameters

items

...Items

one or multiple literal value, function, Result or AsyncResult instance, Promise, or (async) generator function.

Returns

ListContainsAsync<Items> extends true ? AsyncResult<ExtractValues<Unwrapped>, ExtractErrors<Unwrapped>[number]> : Result<ExtractValues<Unwrapped>, ExtractErrors<Unwrapped>[number]>

combined result of all the operations.

NOTE

Any exceptions that might be thrown are not caught, so it is your responsibility to handle these exceptions. Please refer to Result.allCatching for a version that catches exceptions and encapsulates them in a failed result.

Examples

basic usage

ts
declare function createTask(name: string): Result<Task, IOError>;

const tasks = ["task-a", "task-b", "task-c"];
const result = Result.all(...tasks.map(createTask)); // Result<Task[], IOError>

running multiple operations and combining the results

ts
const result = Result.all(
  "a",
  Promise.resolve("b"),
  Result.ok("c"),
  Result.try(async () => "d"),
  () => "e",
  () => Result.try(async () => "f"),
  () => Result.ok("g"),
  async () => "h",
  function* () {
    return "i";
  }
); // AsyncResult<[string, string, string, string, string, string, string, string, string], Error>

allCatching()

static allCatching<Items, Unwrapped>(...items): ListContainsAsync<Items> extends true ? AsyncResult<ExtractValues<Unwrapped>, ExtractErrors<Unwrapped>[number] | AccountForThrowing<Items>> : Result<ExtractValues<Unwrapped>, ExtractErrors<Unwrapped>[number] | AccountForThrowing<Items>>

Defined in: src/result.ts:1847

Similar to Result.all, but catches any exceptions that might be thrown during the operations.

Type Parameters

Items

Items extends any[]

Unwrapped

Unwrapped extends any[] = UnwrapList<Items>

Parameters

items

...Items

one or multiple literal value, function, Result or AsyncResult instance, or Promise.

Returns

ListContainsAsync<Items> extends true ? AsyncResult<ExtractValues<Unwrapped>, ExtractErrors<Unwrapped>[number] | AccountForThrowing<Items>> : Result<ExtractValues<Unwrapped>, ExtractErrors<Unwrapped>[number] | AccountForThrowing<Items>>

combined result of all the operations.


assertError()

static assertError<Err>(result): asserts result is Error<Err>

Defined in: src/result.ts:2306

Asserts that the provided result is a failure. If the result is successful, an error is thrown. Useful in unit tests.

Type Parameters

Err

Err

Parameters

result

Result<any, Err>

the result instance to assert against.

Returns

asserts result is Error<Err>


assertOk()

static assertOk<Value>(result): asserts result is Ok<Value>

Defined in: src/result.ts:2292

Asserts that the provided result is successful. If the result is a failure, an error is thrown. Useful in unit tests.

Type Parameters

Value

Value

Parameters

result

Result<Value, any>

the result instance to assert against.

Returns

asserts result is Ok<Value>


error()

Call Signature

static error<Err>(error): Error<Err>

Defined in: src/result.ts:1640

Creates a new result instance that represents a failed outcome.

Type Parameters
Err

Err extends string

Parameters
error

Err

The error to encapsulate in the result.

Returns

Error<Err>

a new Result instance.

Example
ts
const result = Result.error(new NotFoundError()); // Result.Error<NotFoundError>

Call Signature

static error<Err>(error): Error<Err>

Defined in: src/result.ts:1641

Creates a new result instance that represents a failed outcome.

Type Parameters
Err

Err

Parameters
error

Err

The error to encapsulate in the result.

Returns

Error<Err>

a new Result instance.

Example
ts
const result = Result.error(new NotFoundError()); // Result.Error<NotFoundError>

fromAsync()

Call Signature

static fromAsync<T>(fn): AsyncResult<ExtractValue<T>, ExtractError<T>>

Defined in: src/result.ts:2025

Utility method to transform an async function to an AsyncResult instance. Useful when you want to immediately chain operations after calling an async function/method that returns a Result.

Type Parameters
T

T

Parameters
fn

() => Promise<T>

the async callback function that returns a literal value or a Result or AsyncResult instance.

Returns

AsyncResult<ExtractValue<T>, ExtractError<T>>

a new AsyncResult instance.

NOTE

Any exceptions that might be thrown are not caught, so it is your responsibility to handle these exceptions. Please refer to Result.fromAsyncCatching for a version that catches exceptions and encapsulates them in a failed result.

Example

basic usage

ts
function findUserById(id: string) {
  return Result.fromAsync(async () => {
    const user = await db.query("SELECT * FROM users WHERE id = ?", [id]);

    if (!user) {
      return Result.error(new NotFoundError("User not found"));
    }

    return Result.ok(user);
  });
}

const displayName = await findUserById("123").fold((user) => user.name, () => "Unknown User");

Call Signature

static fromAsync<T>(value): AsyncResult<ExtractValue<T>, ExtractError<T>>

Defined in: src/result.ts:2055

Utility method to transform a Promise, that holds a literal value or a Result or AsyncResult instance, into an AsyncResult instance. Useful when you want to immediately chain operations after calling an async function.

Type Parameters
T

T

Parameters
value

Promise<T>

a Promise that holds a literal value or a Result or AsyncResult instance.

Returns

AsyncResult<ExtractValue<T>, ExtractError<T>>

a new AsyncResult instance.

NOTE

Any exceptions that might be thrown are not caught, so it is your responsibility to handle these exceptions. Please refer to Result.fromAsyncCatching for a version that catches exceptions and encapsulates them in a failed result.

Example

basic usage

ts
declare function someAsyncOperation(): Promise<Result<number, Error>>;

// without 'Result.fromAsync'
const result = (await someAsyncOperation()).map((value) => value * 2); // Result<number, Error>

// with 'Result.fromAsync'
const asyncResult = Result.fromAsync(someAsyncOperation()).map((value) => value * 2); // AsyncResult<number, Error>

fromAsyncCatching()

Call Signature

static fromAsyncCatching<T, ErrorType>(fn, transformError?): AsyncResult<ExtractValue<T>, ErrorType | ExtractError<T>>

Defined in: src/result.ts:2068

Similar to Result.fromAsync this method transforms an async callback function into an AsyncResult instance. In addition, it catches any exceptions that might be thrown during the operation and encapsulates them in a failed result.

Type Parameters
T

T

ErrorType

ErrorType = Error

Parameters
fn

() => Promise<T>

transformError?

(err) => ErrorType

Returns

AsyncResult<ExtractValue<T>, ErrorType | ExtractError<T>>

Call Signature

static fromAsyncCatching<T, ErrorType>(value, transformError?): AsyncResult<ExtractValue<T>, ErrorType | ExtractError<T>>

Defined in: src/result.ts:2076

Similar to Result.fromAsync this method transforms a Promise into an AsyncResult instance. In addition, it catches any exceptions that might be thrown during the operation and encapsulates them in a failed result.

Type Parameters
T

T

ErrorType

ErrorType = Error

Parameters
value

Promise<T>

transformError?

(err) => ErrorType

Returns

AsyncResult<ExtractValue<T>, ErrorType | ExtractError<T>>


gen()

Call Signature

static gen<T>(fn): IfGeneratorAsync<T, AsyncResult<InferGeneratorReturn<T>, InferGeneratorError<T>>, Result<InferGeneratorReturn<T>, InferGeneratorError<T>>>

Defined in: src/result.ts:2170

Executes the given fn (async) generator function and encapsulates the returned value or error as a Result. This method is often used once as entry point to run a specific flow. The reason for this is that nested generator functions or calls to other functions that return results are supported.

Type Parameters
T

T extends Generator<unknown, any, any> | AsyncGenerator<unknown, any, any>

Parameters
fn

() => T

generator function with code to execute. Can be synchronous or asynchronous.

Returns

IfGeneratorAsync<T, AsyncResult<InferGeneratorReturn<T>, InferGeneratorError<T>>, Result<InferGeneratorReturn<T>, InferGeneratorError<T>>>

a new Result or AsyncResult instance depending on the provided callback fn.

Examples

basic usage

ts
const result = Result.gen(async function* () {
   const order = yield* getOrderById("123"); // AsyncResult<Order, NotFoundError>
   yield* order.ship(); // Result<void, InvalidOrderStatusError>;
   const arrivalDate = await shipmentService.calculateArrivalDate(order);
   return `Your order has been shipped and is expected to arrive on ${arrivalDate}!`;
}); // AsyncResult<string, NotFoundError | InvalidOrderStatusError>;

this context

ts
class MyClass {
  someValue = 12;

  someMethod() {
    return Result.gen(this, function* () {
      const otherValue = yield* Result.ok(8);
      return `The sum is ${this.someValue + otherValue}`;
    });
  }
}

Call Signature

static gen<T, This>(self, fn): IfGeneratorAsync<T, AsyncResult<InferGeneratorReturn<T>, InferGeneratorError<T>>, Result<InferGeneratorReturn<T>, InferGeneratorError<T>>>

Defined in: src/result.ts:2177

Executes the given fn (async) generator function and encapsulates the returned value or error as a Result. This method is often used once as entry point to run a specific flow. The reason for this is that nested generator functions or calls to other functions that return results are supported.

Type Parameters
T

T extends Generator<unknown, any, any> | AsyncGenerator<unknown, any, any>

This

This

Parameters
self

This

optional this context to bind the generator function to.

fn

(this) => T

generator function with code to execute. Can be synchronous or asynchronous.

Returns

IfGeneratorAsync<T, AsyncResult<InferGeneratorReturn<T>, InferGeneratorError<T>>, Result<InferGeneratorReturn<T>, InferGeneratorError<T>>>

a new Result or AsyncResult instance depending on the provided callback fn.

Examples

basic usage

ts
const result = Result.gen(async function* () {
   const order = yield* getOrderById("123"); // AsyncResult<Order, NotFoundError>
   yield* order.ship(); // Result<void, InvalidOrderStatusError>;
   const arrivalDate = await shipmentService.calculateArrivalDate(order);
   return `Your order has been shipped and is expected to arrive on ${arrivalDate}!`;
}); // AsyncResult<string, NotFoundError | InvalidOrderStatusError>;

this context

ts
class MyClass {
  someValue = 12;

  someMethod() {
    return Result.gen(this, function* () {
      const otherValue = yield* Result.ok(8);
      return `The sum is ${this.someValue + otherValue}`;
    });
  }
}

Call Signature

static gen<T>(generator): IfGeneratorAsync<T, AsyncResult<InferGeneratorReturn<T>, InferGeneratorError<T>>, Result<InferGeneratorReturn<T>, InferGeneratorError<T>>>

Defined in: src/result.ts:2185

Executes the given fn (async) generator function and encapsulates the returned value or error as a Result. This method is often used once as entry point to run a specific flow. The reason for this is that nested generator functions or calls to other functions that return results are supported.

Type Parameters
T

T extends Generator<unknown, any, any> | AsyncGenerator<unknown, any, any>

Parameters
generator

T

Returns

IfGeneratorAsync<T, AsyncResult<InferGeneratorReturn<T>, InferGeneratorError<T>>, Result<InferGeneratorReturn<T>, InferGeneratorError<T>>>

a new Result or AsyncResult instance depending on the provided callback fn.

Examples

basic usage

ts
const result = Result.gen(async function* () {
   const order = yield* getOrderById("123"); // AsyncResult<Order, NotFoundError>
   yield* order.ship(); // Result<void, InvalidOrderStatusError>;
   const arrivalDate = await shipmentService.calculateArrivalDate(order);
   return `Your order has been shipped and is expected to arrive on ${arrivalDate}!`;
}); // AsyncResult<string, NotFoundError | InvalidOrderStatusError>;

this context

ts
class MyClass {
  someValue = 12;

  someMethod() {
    return Result.gen(this, function* () {
      const otherValue = yield* Result.ok(8);
      return `The sum is ${this.someValue + otherValue}`;
    });
  }
}

genCatching()

Call Signature

static genCatching<T, ErrorType>(generator, transformError?): IfGeneratorAsync<T, AsyncResult<InferGeneratorReturn<T>, ErrorType | InferGeneratorError<T>>, Result<InferGeneratorReturn<T>, ErrorType | InferGeneratorError<T>>>

Defined in: src/result.ts:2210

Similar to Result.gen this method transforms the given generator function into a Result or AsyncResult depending on whether the generator function contains async operations or not. In addition, it catches any exceptions that might be thrown during any operation and encapsulates them in a failed result.

Type Parameters
T

T extends Generator<unknown, any, any> | AsyncGenerator<unknown, any, any>

ErrorType

ErrorType = Error

Parameters
generator

T

transformError?

(error) => ErrorType

Returns

IfGeneratorAsync<T, AsyncResult<InferGeneratorReturn<T>, ErrorType | InferGeneratorError<T>>, Result<InferGeneratorReturn<T>, ErrorType | InferGeneratorError<T>>>

Call Signature

static genCatching<T, ErrorType>(fn, transformError?): IfGeneratorAsync<T, AsyncResult<InferGeneratorReturn<T>, ErrorType | InferGeneratorError<T>>, Result<InferGeneratorReturn<T>, ErrorType | InferGeneratorError<T>>>

Defined in: src/result.ts:2221

Similar to Result.gen this method transforms the given generator function into a Result or AsyncResult depending on whether the generator function contains async operations or not. In addition, it catches any exceptions that might be thrown during any operation and encapsulates them in a failed result.

Type Parameters
T

T extends Generator<unknown, any, any> | AsyncGenerator<unknown, any, any>

ErrorType

ErrorType = Error

Parameters
fn

() => T

transformError?

(error) => ErrorType

Returns

IfGeneratorAsync<T, AsyncResult<InferGeneratorReturn<T>, ErrorType | InferGeneratorError<T>>, Result<InferGeneratorReturn<T>, ErrorType | InferGeneratorError<T>>>

Call Signature

static genCatching<T, This, ErrorType>(self, fn, transformError?): IfGeneratorAsync<T, AsyncResult<InferGeneratorReturn<T>, ErrorType | InferGeneratorError<T>>, Result<InferGeneratorReturn<T>, ErrorType | InferGeneratorError<T>>>

Defined in: src/result.ts:2232

Similar to Result.gen this method transforms the given generator function into a Result or AsyncResult depending on whether the generator function contains async operations or not. In addition, it catches any exceptions that might be thrown during any operation and encapsulates them in a failed result.

Type Parameters
T

T extends Generator<unknown, any, any> | AsyncGenerator<unknown, any, any>

This

This

ErrorType

ErrorType = Error

Parameters
self

This

fn

(this) => T

transformError?

(error) => ErrorType

Returns

IfGeneratorAsync<T, AsyncResult<InferGeneratorReturn<T>, ErrorType | InferGeneratorError<T>>, Result<InferGeneratorReturn<T>, ErrorType | InferGeneratorError<T>>>


isAsyncResult()

static isAsyncResult(possibleAsyncResult): possibleAsyncResult is AnyAsyncResult

Defined in: src/result.ts:1662

Type guard that checks whether the provided value is a AsyncResult instance.

Parameters

possibleAsyncResult

unknown

any value that might be a AsyncResult instance.

Returns

possibleAsyncResult is AnyAsyncResult

true if the provided value is a AsyncResult instance, otherwise false.


isResult()

static isResult(possibleResult): possibleResult is AnyOuterResult

Defined in: src/result.ts:1652

Type guard that checks whether the provided value is a Result instance.

Parameters

possibleResult

unknown

any value that might be a Result instance.

Returns

possibleResult is AnyOuterResult

true if the provided value is a Result instance, otherwise false.


ok()

Call Signature

static ok(): Ok<void>

Defined in: src/result.ts:1623

Creates a new result instance that represents a successful outcome.

Returns

Ok<void>

a new Result instance.

Example
ts
const result = Result.ok(42); // Result.Ok<number>

Call Signature

static ok<Value>(value): Ok<Value>

Defined in: src/result.ts:1624

Creates a new result instance that represents a successful outcome.

Type Parameters
Value

Value

Parameters
value

Value

The value to encapsulate in the result.

Returns

Ok<Value>

a new Result instance.

Example
ts
const result = Result.ok(42); // Result.Ok<number>

try()

Call Signature

static try<R>(fn): IfGeneratorAsync<R, AsyncResult<InferGeneratorReturn<R>, Error | InferGeneratorError<R>>, Result<InferGeneratorReturn<R>, Error | InferGeneratorError<R>>>

Defined in: src/result.ts:1927

Executes the given fn function and encapsulates the returned value as a successful result, or the thrown exception as a failed result. In a way, you can view this method as a try-catch block that returns a result.

Type Parameters
R

R extends Generator<unknown, any, any> | AsyncGenerator<unknown, any, any>

Parameters
fn

() => R

function with code to execute. Can be synchronous or asynchronous.

Returns

IfGeneratorAsync<R, AsyncResult<InferGeneratorReturn<R>, Error | InferGeneratorError<R>>, Result<InferGeneratorReturn<R>, Error | InferGeneratorError<R>>>

a new Result instance.

Examples

basic usage

ts
declare function saveFileToDisk(filename: string): void; // might throw an error

const result = Result.try(() => saveFileToDisk("file.txt")); // Result<void, Error>

basic usage with error transformation

ts
declare function saveFileToDisk(filename: string): void; // might throw an error

const result = Result.try(
  () => saveFileToDisk("file.txt"),
  (error) => new IOError("Failed to save file", { cause: error })
); // Result<void, IOError>

Call Signature

static try<R, ErrorType>(fn, transform): IfGeneratorAsync<R, AsyncResult<InferGeneratorReturn<R>, ErrorType | InferGeneratorError<R>>, Result<InferGeneratorReturn<R>, ErrorType | InferGeneratorError<R>>>

Defined in: src/result.ts:1934

Executes the given fn function and encapsulates the returned value as a successful result, or the thrown exception as a failed result. In a way, you can view this method as a try-catch block that returns a result.

Type Parameters
R

R extends Generator<unknown, any, any> | AsyncGenerator<unknown, any, any>

ErrorType

ErrorType extends AnyValue

Parameters
fn

() => R

function with code to execute. Can be synchronous or asynchronous.

transform

(error) => ErrorType

optional callback to transform the caught error into a more meaningful error.

Returns

IfGeneratorAsync<R, AsyncResult<InferGeneratorReturn<R>, ErrorType | InferGeneratorError<R>>, Result<InferGeneratorReturn<R>, ErrorType | InferGeneratorError<R>>>

a new Result instance.

Examples

basic usage

ts
declare function saveFileToDisk(filename: string): void; // might throw an error

const result = Result.try(() => saveFileToDisk("file.txt")); // Result<void, Error>

basic usage with error transformation

ts
declare function saveFileToDisk(filename: string): void; // might throw an error

const result = Result.try(
  () => saveFileToDisk("file.txt"),
  (error) => new IOError("Failed to save file", { cause: error })
); // Result<void, IOError>

Call Signature

static try<Fn, R>(fn): AsyncResult<InferValue<R>, Error | InferError<R>>

Defined in: src/result.ts:1942

Executes the given fn function and encapsulates the returned value as a successful result, or the thrown exception as a failed result. In a way, you can view this method as a try-catch block that returns a result.

Type Parameters
Fn

Fn extends AnyAsyncFunction<AnyResult>

R

R = Awaited<ReturnType<Fn>>

Parameters
fn

Fn

function with code to execute. Can be synchronous or asynchronous.

Returns

AsyncResult<InferValue<R>, Error | InferError<R>>

a new Result instance.

Examples

basic usage

ts
declare function saveFileToDisk(filename: string): void; // might throw an error

const result = Result.try(() => saveFileToDisk("file.txt")); // Result<void, Error>

basic usage with error transformation

ts
declare function saveFileToDisk(filename: string): void; // might throw an error

const result = Result.try(
  () => saveFileToDisk("file.txt"),
  (error) => new IOError("Failed to save file", { cause: error })
); // Result<void, IOError>

Call Signature

static try<Fn, R>(fn): Result<InferValue<R>, Error | InferError<R>>

Defined in: src/result.ts:1946

Executes the given fn function and encapsulates the returned value as a successful result, or the thrown exception as a failed result. In a way, you can view this method as a try-catch block that returns a result.

Type Parameters
Fn

Fn extends AnyFunction<AnyResult>

R

R = ReturnType<Fn>

Parameters
fn

Fn

function with code to execute. Can be synchronous or asynchronous.

Returns

Result<InferValue<R>, Error | InferError<R>>

a new Result instance.

Examples

basic usage

ts
declare function saveFileToDisk(filename: string): void; // might throw an error

const result = Result.try(() => saveFileToDisk("file.txt")); // Result<void, Error>

basic usage with error transformation

ts
declare function saveFileToDisk(filename: string): void; // might throw an error

const result = Result.try(
  () => saveFileToDisk("file.txt"),
  (error) => new IOError("Failed to save file", { cause: error })
); // Result<void, IOError>

Call Signature

static try<ReturnType>(fn): AsyncResult<Awaited<ReturnType>, Error>

Defined in: src/result.ts:1949

Executes the given fn function and encapsulates the returned value as a successful result, or the thrown exception as a failed result. In a way, you can view this method as a try-catch block that returns a result.

Type Parameters
ReturnType

ReturnType extends AnyPromise

Parameters
fn

() => ReturnType

function with code to execute. Can be synchronous or asynchronous.

Returns

AsyncResult<Awaited<ReturnType>, Error>

a new Result instance.

Examples

basic usage

ts
declare function saveFileToDisk(filename: string): void; // might throw an error

const result = Result.try(() => saveFileToDisk("file.txt")); // Result<void, Error>

basic usage with error transformation

ts
declare function saveFileToDisk(filename: string): void; // might throw an error

const result = Result.try(
  () => saveFileToDisk("file.txt"),
  (error) => new IOError("Failed to save file", { cause: error })
); // Result<void, IOError>

Call Signature

static try<ReturnType>(fn): Result<ReturnType, Error>

Defined in: src/result.ts:1952

Executes the given fn function and encapsulates the returned value as a successful result, or the thrown exception as a failed result. In a way, you can view this method as a try-catch block that returns a result.

Type Parameters
ReturnType

ReturnType

Parameters
fn

() => ReturnType

function with code to execute. Can be synchronous or asynchronous.

Returns

Result<ReturnType, Error>

a new Result instance.

Examples

basic usage

ts
declare function saveFileToDisk(filename: string): void; // might throw an error

const result = Result.try(() => saveFileToDisk("file.txt")); // Result<void, Error>

basic usage with error transformation

ts
declare function saveFileToDisk(filename: string): void; // might throw an error

const result = Result.try(
  () => saveFileToDisk("file.txt"),
  (error) => new IOError("Failed to save file", { cause: error })
); // Result<void, IOError>

Call Signature

static try<ReturnType, ErrorType>(fn, transform): AsyncResult<Awaited<ReturnType>, ErrorType>

Defined in: src/result.ts:1955

Executes the given fn function and encapsulates the returned value as a successful result, or the thrown exception as a failed result. In a way, you can view this method as a try-catch block that returns a result.

Type Parameters
ReturnType

ReturnType extends AnyPromise

ErrorType

ErrorType extends AnyValue

Parameters
fn

() => ReturnType

function with code to execute. Can be synchronous or asynchronous.

transform

(error) => ErrorType

optional callback to transform the caught error into a more meaningful error.

Returns

AsyncResult<Awaited<ReturnType>, ErrorType>

a new Result instance.

Examples

basic usage

ts
declare function saveFileToDisk(filename: string): void; // might throw an error

const result = Result.try(() => saveFileToDisk("file.txt")); // Result<void, Error>

basic usage with error transformation

ts
declare function saveFileToDisk(filename: string): void; // might throw an error

const result = Result.try(
  () => saveFileToDisk("file.txt"),
  (error) => new IOError("Failed to save file", { cause: error })
); // Result<void, IOError>

Call Signature

static try<ReturnType, ErrorType>(fn, transform): Result<ReturnType, ErrorType>

Defined in: src/result.ts:1959

Executes the given fn function and encapsulates the returned value as a successful result, or the thrown exception as a failed result. In a way, you can view this method as a try-catch block that returns a result.

Type Parameters
ReturnType

ReturnType

ErrorType

ErrorType extends AnyValue

Parameters
fn

() => ReturnType

function with code to execute. Can be synchronous or asynchronous.

transform

(error) => ErrorType

optional callback to transform the caught error into a more meaningful error.

Returns

Result<ReturnType, ErrorType>

a new Result instance.

Examples

basic usage

ts
declare function saveFileToDisk(filename: string): void; // might throw an error

const result = Result.try(() => saveFileToDisk("file.txt")); // Result<void, Error>

basic usage with error transformation

ts
declare function saveFileToDisk(filename: string): void; // might throw an error

const result = Result.try(
  () => saveFileToDisk("file.txt"),
  (error) => new IOError("Failed to save file", { cause: error })
); // Result<void, IOError>

wrap()

Call Signature

static wrap<Fn, ErrorType>(fn, transformError?): (...args) => AsyncResult<Awaited<ReturnType<Fn>>, ErrorType>

Defined in: src/result.ts:1881

Wraps a function and returns a new function that returns a result. Especially useful when you want to work with external functions that might throw exceptions. The returned function will catch any exceptions that might be thrown and encapsulate them in a failed result.

Type Parameters
Fn

Fn extends AnyAsyncFunction

ErrorType

ErrorType = Error

Parameters
fn

Fn

function to wrap. Can be synchronous or asynchronous.

transformError?

(error) => ErrorType

Returns

a new function that returns a result.

(...args): AsyncResult<Awaited<ReturnType<Fn>>, ErrorType>

Parameters
args

...Parameters<Fn>

Returns

AsyncResult<Awaited<ReturnType<Fn>>, ErrorType>

Example

basic usage

ts
declare function divide(a: number, b: number): number;

const safeDivide = Result.wrap(divide);
const result = safeDivide(10, 0); // Result<number, Error>

Call Signature

static wrap<Fn, ErrorType>(fn, transformError?): (...args) => Result<ReturnType<Fn>, ErrorType>

Defined in: src/result.ts:1887

Wraps a function and returns a new function that returns a result. Especially useful when you want to work with external functions that might throw exceptions. The returned function will catch any exceptions that might be thrown and encapsulate them in a failed result.

Type Parameters
Fn

Fn extends AnyFunction

ErrorType

ErrorType = Error

Parameters
fn

Fn

function to wrap. Can be synchronous or asynchronous.

transformError?

(error) => ErrorType

Returns

a new function that returns a result.

(...args): Result<ReturnType<Fn>, ErrorType>

Parameters
args

...Parameters<Fn>

Returns

Result<ReturnType<Fn>, ErrorType>

Example

basic usage

ts
declare function divide(a: number, b: number): number;

const safeDivide = Result.wrap(divide);
const result = safeDivide(10, 0); // Result<number, Error>