#Quick Start
This guide walks you through the core workflow of @praha/byethrow in a few minutes.
#Installation
Install the package with your preferred package manager:
npm install @praha/byethrowyarn add @praha/byethrowpnpm add @praha/byethrowbun add @praha/byethrowdeno add npm:@praha/byethrow#Your First Result
A Result is either a Success that holds a value, or a Failure that holds an error.
Create them with Result.succeed and Result.fail, and return them instead of throwing:
import { import Result Result } from '@praha/byethrow';
const const divide: (a: number, b: number) => Result.Failure<Error> | Result.Success<number> divide = (a: number a : number, b: number b : number) => {
if (b: number b === 0) {
return import Result Result .function fail<Error>(error: Error): Result.Result<never, Error> (+1 overload)Creates a
Failure
result from a given error.
Passing a Promise is allowed, but it is recommended to await it before passing to fail.
@typeParamE - The type of the error to wrap.@returnsA Result containing the given error.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.fail('Something went wrong');
// Result.Result<never, string>
@exampleWith No Value
import { Result } from '@praha/byethrow';
const result = Result.fail();
// Result.Result<never, void>
@seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators fail (new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error ('Cannot divide by zero'));
}
return import Result Result .function succeed<number>(value: number): Result.Result<number, never> (+1 overload)Creates a
Success
result from a given value.
Passing a Promise is allowed, but it is recommended to await it before passing to succeed.
@typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith No Value
import { Result } from '@praha/byethrow';
const result = Result.succeed();
// Result.Result<void, never>
@seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators succeed (a: number a / b: number b );
};To read the contents, first check which variant you have with Result.isSuccess or Result.isFailure.
TypeScript then knows whether value or error is available:
const const result: Result.Result<number, Error> result = const divide: (a: number, b: number) => Result.Result<number, Error> divide (10, 2);
if (import Result Result .function isSuccess<Result.Result<number, Error>>(result: Result.Result<number, Error>): result is Result.Success<number>Type guard to check if a
Result
is a
Success
.
@typeParamR - The type of the result to check.@paramresult - The Result to check.@returnstrue if the result is a Success , otherwise false.@exampleimport { Result } from '@praha/byethrow';
const result: Result.Result<number, string> = { type: 'Success', value: 10 };
if (Result.isSuccess(result)) {
console.log(result.value); // Safe access to value
}
@categoryType Guards isSuccess (const result: Result.Result<number, Error> result )) {
var console: Console console .Console.log(...data: any[]): voidThe console.log() static method outputs a message to the console.
log (const result: Result.Success<number> result .value: number value ); // 5
} else {
var console: Console console .Console.error(...data: any[]): voidThe console.error() static method outputs a message to the console at the "error" log level. The message is only displayed to the user if the console is configured to display error output. In most cases, the log level is configured within the console UI. The message may be formatted as an error, with red colors and call stack information.
error (const result: Result.Failure<Error> result .error: Error error .Error.message: string message );
}#Wrapping Code That Throws
Existing code, built-in APIs, and third-party libraries often throw.
Result.fn wraps such a function so that it returns a Result instead:
import { import Result Result } from '@praha/byethrow';
const const parseJson: (text: string) => Result.Result<unknown, Error> parseJson = import Result Result .function fn<(text: string) => unknown, Error>(options: {
try: (text: string) => unknown;
catch: (error: unknown) => Error;
}): (text: string) => Result.Result<unknown, Error> (+3 overloads)
Wraps a function that may throw and returns a new function that returns a
Result
or
ResultAsync
.
You can use either a custom catch handler or rely on the safe: true option
to assume the function cannot throw.
@typeParamT - The function type to execute (sync or async) or a Promise type.@typeParamE - The error type to return if catch is used.@returnsA new function that returns a Result or ResultAsync wrapping the original function's return value or the caught error.@exampleSync try-catch
import { Result } from '@praha/byethrow';
const fn = Result.fn({
try: (x: number) => {
if (x < 0) throw new Error('Negative!');
return x * 2;
},
catch: (error) => new Error('Oops!', { cause: error }),
});
const result = fn(5); // Result.Result<number, Error>
@exampleSync safe
import { Result } from '@praha/byethrow';
const fn = Result.fn({
safe: true,
try: (x: number) => x + 1,
});
const result = fn(1); // Result.Result<number, never>
@exampleAsync try-catch
import { Result } from '@praha/byethrow';
const fn = Result.fn({
try: async (id: string) => await fetch(`/api/data/${id}`),
catch: (error) => new Error('Oops!', { cause: error }),
});
const result = await fn('abc'); // Result.ResultAsync<Response, Error>
@exampleAsync safe
import { Result } from '@praha/byethrow';
const fn = Result.fn({
safe: true,
try: async () => await Promise.resolve('ok'),
});
const result = await fn(); // Result.ResultAsync<string, never>
@categoryCreators fn ({
try: (text: string) => unknown try : (text: string text : string) => var JSON: JSONAn intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
JSON .JSON.parse(text: string, reviver?: (this: any, key: string, value: any) => any): anyConverts a JavaScript Object Notation (JSON) string into an object.
@paramtext A valid JSON string.@paramreviver A function that transforms the results. This function is called for each member of the object.
If a member contains nested objects, the nested objects are transformed before the parent object is.@throws{SyntaxError} If text is not valid JSON. parse (text: string text ) as unknown,
catch: (error: unknown) => Error catch : (error: unknown error ) => new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error ('Invalid JSON', { ErrorOptions.cause?: unknown cause : error: unknown error }),
});
const parseJson: (text: string) => Result.Result<unknown, Error> parseJson ('{"name": "Alice"}');
// { type: 'Success', value: { name: 'Alice' } }
const parseJson: (text: string) => Result.Result<unknown, Error> parseJson ('not json');
// { type: 'Failure', error: Error('Invalid JSON') }#Composing Steps with pipe
Result.pipe passes a value through a series of steps from top to bottom.
Use Result.andThen for steps that can fail (they return a Result), and Result.map for steps that simply transform the value:
import { import Result Result } from '@praha/byethrow';
const const validateId: (id: string) => Result.Failure<Error> | Result.Success<string> validateId = (id: string id : string) => {
if (!id: string id .String.startsWith(searchString: string, position?: number): booleanReturns true if the sequence of elements of searchString converted to a String is the
same as the corresponding elements of this object (converted to a String) starting at
position. Otherwise returns false.
startsWith ('u')) {
return import Result Result .function fail<Error>(error: Error): Result.Result<never, Error> (+1 overload)Creates a
Failure
result from a given error.
Passing a Promise is allowed, but it is recommended to await it before passing to fail.
@typeParamE - The type of the error to wrap.@returnsA Result containing the given error.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.fail('Something went wrong');
// Result.Result<never, string>
@exampleWith No Value
import { Result } from '@praha/byethrow';
const result = Result.fail();
// Result.Result<never, void>
@seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators fail (new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error ('Invalid ID format'));
}
return import Result Result .function succeed<string>(value: string): Result.Result<string, never> (+1 overload)Creates a
Success
result from a given value.
Passing a Promise is allowed, but it is recommended to await it before passing to succeed.
@typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith No Value
import { Result } from '@praha/byethrow';
const result = Result.succeed();
// Result.Result<void, never>
@seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators succeed (id: string id );
};
const const findUser: (id: string) => Result.Failure<Error> | Result.Success<{
readonly id: "u123";
readonly name: "John Doe";
}>
findUser = (id: string id : string) => {
if (id: string id !== 'u123') {
return import Result Result .function fail<Error>(error: Error): Result.Result<never, Error> (+1 overload)Creates a
Failure
result from a given error.
Passing a Promise is allowed, but it is recommended to await it before passing to fail.
@typeParamE - The type of the error to wrap.@returnsA Result containing the given error.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.fail('Something went wrong');
// Result.Result<never, string>
@exampleWith No Value
import { Result } from '@praha/byethrow';
const result = Result.fail();
// Result.Result<never, void>
@seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators fail (new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error ('User not found'));
}
return import Result Result .function succeed<{
readonly id: "u123";
readonly name: "John Doe";
}>(value: {
readonly id: "u123";
readonly name: "John Doe";
}): Result.Result<{
readonly id: "u123";
readonly name: "John Doe";
}, never> (+1 overload)
Creates a
Success
result from a given value.
Passing a Promise is allowed, but it is recommended to await it before passing to succeed.
@typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith No Value
import { Result } from '@praha/byethrow';
const result = Result.succeed();
// Result.Result<void, never>
@seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators succeed ({ id: "u123" id , name: "John Doe" name : 'John Doe' });
};
const const welcome: (id: string) => Result.Result<"Welcome, John Doe!", Error> welcome = (id: string id : string) => import Result Result .function pipe<Result.Result<string, never>, Result.Result<string, Error>, Result.Result<{
readonly id: "u123";
readonly name: "John Doe";
}, Error>, Result.Result<"Welcome, John Doe!", Error>>(a: Result.Result<string, never>, ab: (a: Result.Result<string, never>) => Result.Result<string, Error>, bc: (b: Result.Result<string, Error>) => Result.Result<{
readonly id: "u123";
readonly name: "John Doe";
}, Error>, cd: (c: Result.Result<{
readonly id: "u123";
readonly name: "John Doe";
}, Error>) => Result.Result<...>): Result.Result<...> (+25 overloads)
Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
import Result Result .function succeed<string>(value: string): Result.Result<string, never> (+1 overload)Creates a
Success
result from a given value.
Passing a Promise is allowed, but it is recommended to await it before passing to succeed.
@typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith No Value
import { Result } from '@praha/byethrow';
const result = Result.succeed();
// Result.Result<void, never>
@seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators succeed (id: string id ),
import Result Result .function andThen<Result.Result<string, never>, Result.Failure<Error> | Result.Success<string>>(fn: (a: string) => Result.Failure<Error> | Result.Success<string>): (result: Result.Result<string, never>) => Result.Result<string, Error> (+1 overload)Chains the next computation using the success value of a
Result
or
ResultAsync
.
If the original result is a
Failure
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(3),
Result.andThen((x) => Result.succeed(x * 2)),
);
// { type: 'Success', value: 6 }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.andThen((x) => Result.succeed(x * 2)),
);
// result: { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(3),
Result.andThen((x) => Result.fail('error: ' + x)),
);
// result: { type: 'Failure', error: 'error: 3' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThen (const validateId: (id: string) => Result.Failure<Error> | Result.Success<string> validateId ),
import Result Result .function andThen<Result.Result<string, Error>, Result.Failure<Error> | Result.Success<{
readonly id: "u123";
readonly name: "John Doe";
}>>(fn: (a: string) => Result.Failure<Error> | Result.Success<{
readonly id: "u123";
readonly name: "John Doe";
}>): (result: Result.Result<string, Error>) => Result.Result<{
readonly id: "u123";
readonly name: "John Doe";
}, Error> (+1 overload)
Chains the next computation using the success value of a
Result
or
ResultAsync
.
If the original result is a
Failure
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(3),
Result.andThen((x) => Result.succeed(x * 2)),
);
// { type: 'Success', value: 6 }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.andThen((x) => Result.succeed(x * 2)),
);
// result: { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(3),
Result.andThen((x) => Result.fail('error: ' + x)),
);
// result: { type: 'Failure', error: 'error: 3' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThen (const findUser: (id: string) => Result.Failure<Error> | Result.Success<{
readonly id: "u123";
readonly name: "John Doe";
}>
findUser ),
import Result Result .function map<Result.Result<{
readonly id: "u123";
readonly name: "John Doe";
}, Error>, "Welcome, John Doe!">(fn: (a: {
readonly id: "u123";
readonly name: "John Doe";
}) => "Welcome, John Doe!"): (result: Result.Result<{
readonly id: "u123";
readonly name: "John Doe";
}, Error>) => Result.Result<"Welcome, John Doe!", Error> (+1 overload)
Applies a transformation function to the success value of a
Result
or
ResultAsync
.
If the input is a
Failure
, it will be returned unchanged.
@typeParamR1 - The input Result or ResultAsync .@typeParamT2 - The transformed success value type.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(2),
Result.map((x) => x * 10),
);
// { type: 'Success', value: 20 }
@exampleFailure Case (unchanged)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.map((x) => x * 10),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators map ((user: {
readonly id: "u123";
readonly name: "John Doe";
}
user ) => `Welcome, ${user: {
readonly id: "u123";
readonly name: "John Doe";
}
user .name: "John Doe" name }!`),
);
const welcome: (id: string) => Result.Result<"Welcome, John Doe!", Error> welcome ('u123');
// { type: 'Success', value: 'Welcome, John Doe!' }
const welcome: (id: string) => Result.Result<"Welcome, John Doe!", Error> welcome ('x999');
// { type: 'Failure', error: Error('Invalid ID format') }As soon as a step fails, the remaining steps are skipped and the failure is passed straight to the end of the pipeline. You don't need to check for errors after every step.
Result.succeed(id),Result.andThen(validateId),Result.andThen(findUser),Result.map(toWelcomeMessage),#Recovering from Failures
Use Result.orElse to handle a failure and continue with a fallback:
const const result: Result.Result<string, never> result = import Result Result .function pipe<Result.Result<string, Error>, Result.Result<string, never>>(a: Result.Result<string, Error>, ab: (a: Result.Result<string, Error>) => Result.Result<string, never>): Result.Result<string, never> (+25 overloads)Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
const welcome: (id: string) => Result.Result<string, Error> welcome ('x999'),
import Result Result .function orElse<Result.Result<string, Error>, Result.Result<"Welcome, guest!", never>>(fn: (a: Error) => Result.Result<"Welcome, guest!", never>): (result: Result.Result<string, Error>) => Result.Result<string, never> (+1 overload)Chains the next computation using the error value of a
Result
or
ResultAsync
.
If the original result is a
Success
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(42),
Result.orElse((error) => Result.succeed(0)),
);
// { type: 'Success', value: 42 }
@exampleFailure Case (function returns a Success)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('original error'),
Result.orElse((error) => Result.succeed('default value')),
);
// result: { type: 'Success', value: 'default value' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('original error'),
Result.orElse((error) => Result.fail('new error: ' + error)),
);
// result: { type: 'Failure', error: 'new error: original error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators orElse (() => import Result Result .function succeed<"Welcome, guest!">(value: "Welcome, guest!"): Result.Result<"Welcome, guest!", never> (+1 overload)Creates a
Success
result from a given value.
Passing a Promise is allowed, but it is recommended to await it before passing to succeed.
@typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith No Value
import { Result } from '@praha/byethrow';
const result = Result.succeed();
// Result.Result<void, never>
@seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators succeed ('Welcome, guest!')),
);
// { type: 'Success', value: 'Welcome, guest!' }#Working with Async Operations
Async functions work with exactly the same API.
When any step returns a Promise, the whole pipeline becomes asynchronous, so just await the result:
const const fetchUser: (id: string) => Result.ResultAsync<User, Error> fetchUser = import Result Result .function fn<(id: string) => Promise<User>, Error>(options: {
try: (id: string) => Promise<User>;
catch: (error: unknown) => Error;
}): (id: string) => Result.ResultAsync<User, Error> (+3 overloads)
Wraps a function that may throw and returns a new function that returns a
Result
or
ResultAsync
.
You can use either a custom catch handler or rely on the safe: true option
to assume the function cannot throw.
@typeParamT - The function type to execute (sync or async) or a Promise type.@typeParamE - The error type to return if catch is used.@returnsA new function that returns a Result or ResultAsync wrapping the original function's return value or the caught error.@exampleSync try-catch
import { Result } from '@praha/byethrow';
const fn = Result.fn({
try: (x: number) => {
if (x < 0) throw new Error('Negative!');
return x * 2;
},
catch: (error) => new Error('Oops!', { cause: error }),
});
const result = fn(5); // Result.Result<number, Error>
@exampleSync safe
import { Result } from '@praha/byethrow';
const fn = Result.fn({
safe: true,
try: (x: number) => x + 1,
});
const result = fn(1); // Result.Result<number, never>
@exampleAsync try-catch
import { Result } from '@praha/byethrow';
const fn = Result.fn({
try: async (id: string) => await fetch(`/api/data/${id}`),
catch: (error) => new Error('Oops!', { cause: error }),
});
const result = await fn('abc'); // Result.ResultAsync<Response, Error>
@exampleAsync safe
import { Result } from '@praha/byethrow';
const fn = Result.fn({
safe: true,
try: async () => await Promise.resolve('ok'),
});
const result = await fn(); // Result.ResultAsync<string, never>
@categoryCreators fn ({
try: (id: string) => Promise<User> try : async (id: string id : string) => {
const const response: Response response = await function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> fetch (`/api/users/${id: string id }`);
return await const response: Response response .Body.json(): Promise<any> json () as type User = {
id: string;
name: string;
}
User ;
},
catch: (error: unknown) => Error catch : (error: unknown error ) => new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error ('Failed to fetch user', { ErrorOptions.cause?: unknown cause : error: unknown error }),
});
const const result: Result.Result<string, Error> result = await import Result Result .function pipe<Result.Result<"u123", never>, Result.Result<string, Error>, Result.ResultAsync<User, Error>, Result.ResultAsync<string, Error>>(a: Result.Result<"u123", never>, ab: (a: Result.Result<"u123", never>) => Result.Result<string, Error>, bc: (b: Result.Result<string, Error>) => Result.ResultAsync<User, Error>, cd: (c: Result.ResultAsync<User, Error>) => Result.ResultAsync<string, Error>): Result.ResultAsync<...> (+25 overloads)Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
import Result Result .function succeed<"u123">(value: "u123"): Result.Result<"u123", never> (+1 overload)Creates a
Success
result from a given value.
Passing a Promise is allowed, but it is recommended to await it before passing to succeed.
@typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith No Value
import { Result } from '@praha/byethrow';
const result = Result.succeed();
// Result.Result<void, never>
@seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators succeed ('u123'),
import Result Result .function andThen<Result.Result<"u123", never>, Result.Result<string, Error>>(fn: (a: "u123") => Result.Result<string, Error>): (result: Result.Result<"u123", never>) => Result.Result<string, Error> (+1 overload)Chains the next computation using the success value of a
Result
or
ResultAsync
.
If the original result is a
Failure
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(3),
Result.andThen((x) => Result.succeed(x * 2)),
);
// { type: 'Success', value: 6 }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.andThen((x) => Result.succeed(x * 2)),
);
// result: { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(3),
Result.andThen((x) => Result.fail('error: ' + x)),
);
// result: { type: 'Failure', error: 'error: 3' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThen (const validateId: (id: string) => Result.Result<string, Error> validateId ), // sync
import Result Result .function andThen<Result.Result<string, Error>, Result.ResultAsync<User, Error>>(fn: (a: string) => Result.ResultAsync<User, Error>): (result: Result.Result<string, Error>) => Result.ResultAsync<User, Error> (+1 overload)Chains the next computation using the success value of a
Result
or
ResultAsync
.
If the original result is a
Failure
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(3),
Result.andThen((x) => Result.succeed(x * 2)),
);
// { type: 'Success', value: 6 }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.andThen((x) => Result.succeed(x * 2)),
);
// result: { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(3),
Result.andThen((x) => Result.fail('error: ' + x)),
);
// result: { type: 'Failure', error: 'error: 3' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThen (const fetchUser: (id: string) => Result.ResultAsync<User, Error> fetchUser ), // async
import Result Result .function map<Result.ResultAsync<User, Error>, string>(fn: (a: User) => string): (result: Result.ResultAsync<User, Error>) => Result.ResultAsync<string, Error> (+1 overload)Applies a transformation function to the success value of a
Result
or
ResultAsync
.
If the input is a
Failure
, it will be returned unchanged.
@typeParamR1 - The input Result or ResultAsync .@typeParamT2 - The transformed success value type.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(2),
Result.map((x) => x * 10),
);
// { type: 'Success', value: 20 }
@exampleFailure Case (unchanged)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.map((x) => x * 10),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators map ((user: User user ) => user: User user .name: string name ),
);
// Type: Result.Result<string, Error>#Next Steps
- Tutorial: Learn every function in depth, step by step.
- Custom Error: Replace generic
Errorobjects with specific error types. - Linter Plugin and Testing: Keep your codebase consistent and your tests expressive.
- Examples: See byethrow in complete, runnable projects.
