#Result Type
Before diving into the functions, let's look at what the Result type is and why it is useful.
#What Is a Result?
A Result represents the outcome of an operation that might fail.
It is always one of two variants:
- Success: The operation succeeded and holds a
value. - Failure: The operation failed and holds an
error.
Unlike throwing an exception, returning a Result encodes the possibility of failure in the type system itself.
#The Structure
A Result is a plain object with a type property that tells the two variants apart:
import { import Result Result } from '@praha/byethrow';
// A Success holds a value
const const success: Result.Success<number> success : import Result Result .type Success<T> = {
readonly type: "Success";
readonly value: T;
}
Represents a successful result.
@typeParamT - The type of the successful value.@exampleimport { Result } from '@praha/byethrow';
const success: Result.Success<number> = {
type: 'Success',
value: 42,
};
@categoryCore Types Success <number> = {
type: "Success" type : 'Success',
value: number value : 42,
};
// A Failure holds an error
const const failure: Result.Failure<string> failure : import Result Result .type Failure<E> = {
readonly type: "Failure";
readonly error: E;
}
Represents a failed result.
@typeParamE - The type of the error.@exampleimport { Result } from '@praha/byethrow';
const failure: Result.Failure<string> = {
type: 'Failure',
error: 'Something went wrong',
};
@categoryCore Types Failure <string> = {
type: "Failure" type : 'Failure',
error: string error : 'Something went wrong',
};Because it is just an object, a Result can be logged, serialized to JSON, or compared in tests as it is.
In practice, you rarely write these objects by hand. The next page shows the helper functions that create them.
#The Union Type
Result.Result<T, E> is the union of Success<T> and Failure<E>.
T is the type of the success value, and E is the type of the error:
import { import Result Result } from '@praha/byethrow';
// Returns either a Success<number> or a Failure<string>
const const divide: (a: number, b: number) => Result.Result<number, string> divide = (a: number a : number, b: number b : number): import Result Result .type Result<T, E> = Result.Success<T> | Result.Failure<E>A union type representing either a success or a failure.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const doSomething = (): Result.Result<number, string> => {
return Math.random() > 0.5
? { type: 'Success', value: 10 }
: { type: 'Failure', error: 'Oops' };
};
@categoryCore Types Result <number, string> => {
if (b: number b === 0) {
return { type: "Failure" type : 'Failure', error: string error : 'Cannot divide by zero' };
}
return { type: "Success" type : 'Success', value: number value : a: number a / b: number b };
};
const const result: Result.Result<number, string> result = const divide: (a: number, b: number) => Result.Result<number, string> divide (10, 2);
// Type: Result.Result<number, string>#Why Use Result Instead of Exceptions?
#1. Failures Are Visible in the Signature
With exceptions, you can't tell from the signature whether a function might throw:
// ❌ Does this throw? We can't tell from the signature
const const parseConfig: (path: string) => Config parseConfig = (path: string path : string): type Config = {
host: string;
port: number;
}
Config => {
// ...
}With Result, the return type makes it clear:
// ✅ The return type tells us this might fail, and how
const const parseConfig: (path: string) => Result.Result<Config, ParseError> parseConfig = (path: string path : string): import Result Result .type Result<T, E> = Result.Success<T> | Result.Failure<E>A union type representing either a success or a failure.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const doSomething = (): Result.Result<number, string> => {
return Math.random() > 0.5
? { type: 'Success', value: 10 }
: { type: 'Failure', error: 'Oops' };
};
@categoryCore Types Result <type Config = {
host: string;
port: number;
}
Config , class ParseError ParseError > => {
// ...
}#2. Errors Keep Their Types
A caught exception is always unknown. A Result preserves the exact error type:
import { import Result Result } from '@praha/byethrow';
type type ValidationError = {
field: string;
message: string;
}
ValidationError = { field: string field : string; message: string message : string };
const const validateEmail: (email: string) => Result.Result<string, ValidationError> validateEmail = (email: string email : string): import Result Result .type Result<T, E> = Result.Success<T> | Result.Failure<E>A union type representing either a success or a failure.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const doSomething = (): Result.Result<number, string> => {
return Math.random() > 0.5
? { type: 'Success', value: 10 }
: { type: 'Failure', error: 'Oops' };
};
@categoryCore Types Result <string, type ValidationError = {
field: string;
message: string;
}
ValidationError > => {
if (!email: string email .String.includes(searchString: string, position?: number): booleanReturns true if searchString appears as a substring of the result of converting this
object to a String, at one or more positions that are
greater than or equal to position; otherwise, returns false.
@paramsearchString search string@paramposition If position is undefined, 0 is assumed, so as to search all of the String. includes ('@')) {
return import Result Result .function fail<{
readonly field: "email";
readonly message: "Invalid email format";
}>(error: {
readonly field: "email";
readonly message: "Invalid email format";
}): Result.Result<never, {
readonly field: "email";
readonly message: "Invalid email format";
}> (+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 ({ field: "email" field : 'email', message: "Invalid email format" message : 'Invalid email 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 (email: string email );
};
const const result: Result.Result<string, ValidationError> result = const validateEmail: (email: string) => Result.Result<string, ValidationError> validateEmail ('test');
if (import Result Result .function isFailure<Result.Result<string, ValidationError>>(result: Result.Result<string, ValidationError>): result is Result.Failure<ValidationError>Type guard to check if a
Result
is a
Failure
.
@typeParamR - The type of the result to check.@paramresult - The Result to check.@returnstrue if the result is a Failure , otherwise false.@exampleimport { Result } from '@praha/byethrow';
const result: Result.Result<number, string> = { type: 'Failure', error: 'Something went wrong' };
if (Result.isFailure(result)) {
console.error(result.error); // Safe access to error
}
@categoryType Guards isFailure (const result: Result.Result<string, ValidationError> result )) {
// TypeScript knows result.error is ValidationError
var console: Console console .Console.log(...data: any[]): voidThe console.log() static method outputs a message to the console.
log (`Error in ${const result: Result.Failure<ValidationError> result .error: ValidationError error .field: string field }: ${const result: Result.Failure<ValidationError> result .error: ValidationError error .message: string message }`);
}#3. Results Compose
Results can be chained, and the error types of every step are collected into a union automatically. You will learn how this works in the Chaining Operations chapter:
import { import Result Result } from '@praha/byethrow';
const const result: Result.ResultAsync<User, ValidationError | TransformError | SaveError> result = import Result Result .function pipe<Result.Result<{
id: string;
name: string;
}, never>, Result.Result<User, ValidationError>, Result.Result<User, ValidationError | TransformError>, Result.ResultAsync<User, ValidationError | TransformError | SaveError>>(a: Result.Result<{
id: string;
name: string;
}, never>, ab: (a: Result.Result<{
id: string;
name: string;
}, never>) => Result.Result<User, ValidationError>, bc: (b: Result.Result<...>) => Result.Result<...>, cd: (c: Result.Result<...>) => Result.ResultAsync<...>): 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<{
id: string;
name: string;
}>(value: {
id: string;
name: string;
}): Result.Result<{
id: string;
name: 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 (const input: {
id: string;
name: string;
}
input ),
import Result Result .function andThen<Result.Result<{
id: string;
name: string;
}, never>, Result.Result<User, ValidationError>>(fn: (a: {
id: string;
name: string;
}) => Result.Result<User, ValidationError>): (result: Result.Result<{
id: string;
name: string;
}, never>) => Result.Result<User, ValidationError> (+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 validate: (value: User) => Result.Result<User, ValidationError> validate ),
import Result Result .function andThen<Result.Result<User, ValidationError>, Result.Result<User, TransformError>>(fn: (a: User) => Result.Result<User, TransformError>): (result: Result.Result<User, ValidationError>) => Result.Result<User, ValidationError | TransformError> (+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 transform: (value: User) => Result.Result<User, TransformError> transform ),
import Result Result .function andThen<Result.Result<User, ValidationError | TransformError>, Result.ResultAsync<User, SaveError>>(fn: (a: User) => Result.ResultAsync<User, SaveError>): (result: Result.Result<User, ValidationError | TransformError>) => Result.ResultAsync<User, ValidationError | TransformError | SaveError> (+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 save: (value: User) => Result.ResultAsync<User, SaveError> save ),
);
// Type: Result.ResultAsync<User, ValidationError | TransformError | SaveError>#Async Results
An asynchronous Result is represented by ResultAsync<T, E>, which is simply an alias for Promise<Result<T, E>>:
import { import Result Result } from '@praha/byethrow';
const const asyncResult: Result.ResultAsync<number, never> asyncResult : import Result Result .type ResultAsync<T, E> = Promise<Result.Result<T, E>>An asynchronous variant of
Result
, wrapped in a Promise.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const fetchData = async (): Result.ResultAsync<string, Error> => {
try {
const data = await fetch('...');
return { type: 'Success', value: await data.text() };
} catch (err) {
return { type: 'Failure', error: err as Error };
}
};
@categoryCore Types ResultAsync <number, never> = var Promise: PromiseConstructorRepresents the completion of an asynchronous operation
Promise .PromiseConstructor.resolve<Result.Result<42, never>>(value: Result.Result<42, never>): Promise<Result.Result<42, never>> (+2 overloads)Creates a new resolved promise for the provided value.
@paramvalue A promise.@returnsA promise whose internal state matches the provided promise. resolve (import Result Result .function succeed<42>(value: 42): Result.Result<42, 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 (42));
// Type: Result.ResultAsync<number, never>
// Since ResultAsync is just a Promise, you can await it
const const resolved: Result.Result<number, never> resolved = await const asyncResult: Result.ResultAsync<number, never> asyncResult ;
// Type: Result.Result<number, never>#Mixing Sync and Async
Every function in @praha/byethrow accepts both Result and ResultAsync.
When you mix synchronous and asynchronous steps in a pipeline, the result automatically becomes a ResultAsync from the first async step onward:
import { import Result Result } from '@praha/byethrow';
// Sync function
const const validate: (input: string) => Result.Result<string, Error> validate = (input: string input : string): import Result Result .type Result<T, E> = Result.Success<T> | Result.Failure<E>A union type representing either a success or a failure.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const doSomething = (): Result.Result<number, string> => {
return Math.random() > 0.5
? { type: 'Success', value: 10 }
: { type: 'Failure', error: 'Oops' };
};
@categoryCore Types Result <string, Error> => {
if (input: string input .String.length: numberReturns the length of a String object.
length === 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 ('Input is empty'));
}
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 (input: string input );
};
// Async function
const const fetchData: (input: string) => Result.ResultAsync<number, Error> fetchData = async (input: string input : string): import Result Result .type ResultAsync<T, E> = Promise<Result.Result<T, E>>An asynchronous variant of
Result
, wrapped in a Promise.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const fetchData = async (): Result.ResultAsync<string, Error> => {
try {
const data = await fetch('...');
return { type: 'Success', value: await data.text() };
} catch (err) {
return { type: 'Failure', error: err as Error };
}
};
@categoryCore Types ResultAsync <number, Error> => {
// Simulating an API call
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 (input: string input .String.length: numberReturns the length of a String object.
length );
};
const const result: Result.ResultAsync<number, Error> result = import Result Result .function pipe<Result.Result<"hello", never>, Result.Result<string, Error>, Result.ResultAsync<number, Error>, Result.ResultAsync<number, Error>>(a: Result.Result<"hello", never>, ab: (a: Result.Result<"hello", never>) => Result.Result<string, Error>, bc: (b: Result.Result<string, Error>) => Result.ResultAsync<number, Error>, cd: (c: Result.ResultAsync<number, Error>) => Result.ResultAsync<number, 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<"hello">(value: "hello"): Result.Result<"hello", 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 ('hello'),
import Result Result .function andThen<Result.Result<"hello", never>, Result.Result<string, Error>>(fn: (a: "hello") => Result.Result<string, Error>): (result: Result.Result<"hello", 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 validate: (input: string) => Result.Result<string, Error> validate ), // sync
import Result Result .function andThen<Result.Result<string, Error>, Result.ResultAsync<number, Error>>(fn: (a: string) => Result.ResultAsync<number, Error>): (result: Result.Result<string, Error>) => Result.ResultAsync<number, 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 fetchData: (input: string) => Result.ResultAsync<number, Error> fetchData ), // async: the pipeline becomes async from here
import Result Result .function andThen<Result.ResultAsync<number, Error>, Result.Result<number, never>>(fn: (a: number) => Result.Result<number, never>): (result: Result.ResultAsync<number, Error>) => Result.ResultAsync<number, 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 ((n: number n ) => 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 (n: number n * 2)), // sync, but runs in the async pipeline
);
// Type: Result.ResultAsync<number, Error>#Utility Types
The library also provides a few types that help when writing your own functions around Result.
#ResultMaybeAsync
ResultMaybeAsync<T, E> is either a Result<T, E> or a ResultAsync<T, E>.
It is useful when an implementation may be either synchronous or asynchronous:
import { import Result Result } from '@praha/byethrow';
type type User = {
id: string;
name: string;
}
User = { id: string id : string; name: string name : string };
type type UserRepository = {
findById: (id: string) => Result.ResultMaybeAsync<User, "NotFound">;
}
UserRepository = {
// Both sync (e.g. in-memory) and async (e.g. database) implementations are allowed
findById: (id: string) => Result.ResultMaybeAsync<User, "NotFound"> findById : (id: string id : string) => import Result Result .type ResultMaybeAsync<T, E> = Result.Result<T, E> | Promise<Result.Result<T, E>>A result that may be either synchronous or asynchronous.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleSynchronous Case
import { Result } from '@praha/byethrow';
const result: Result.ResultMaybeAsync<number, string> = { type: 'Success', value: 10 };
@exampleAsynchronous Case
import { Result } from '@praha/byethrow';
const result: Result.ResultMaybeAsync<number, string> = Promise.resolve({ type: 'Failure', error: 'error' });
@categoryCore Types ResultMaybeAsync <type User = {
id: string;
name: string;
}
User , 'NotFound'>;
};#InferSuccess and InferFailure
InferSuccess and InferFailure extract the success and error types from a Result type, or from a function that returns one:
import { import Result Result } from '@praha/byethrow';
declare const const findUser: (id: string) => Result.ResultAsync<{
id: string;
name: string;
}, "NotFound">
findUser : (id: string id : string) => import Result Result .type ResultAsync<T, E> = Promise<Result.Result<T, E>>An asynchronous variant of
Result
, wrapped in a Promise.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const fetchData = async (): Result.ResultAsync<string, Error> => {
try {
const data = await fetch('...');
return { type: 'Success', value: await data.text() };
} catch (err) {
return { type: 'Failure', error: err as Error };
}
};
@categoryCore Types ResultAsync <{ id: string id : string; name: string name : string }, 'NotFound'>;
type type User = {
id: string;
name: string;
}
User = import Result Result .type InferSuccess<T> = [T] extends [(...args: any[]) => Result.ResultMaybeAsync<infer U, any>] ? U : [T] extends [Result.ResultMaybeAsync<infer U, any>] ? U : neverInfers the
Success
value type T from a Result or a function returning a Result.
@typeParamT - A ResultMaybeAsync type or a function returning it.@exampleFrom a result object
import { Result } from '@praha/byethrow';
type R = Result.Result<number, string>;
type SuccessValue = Result.InferSuccess<R>; // number
@exampleFrom a function
import { Result } from '@praha/byethrow';
const fn = () => Promise.resolve({ type: 'Success', value: 123 } as const);
type SuccessValue = Result.InferSuccess<typeof fn>; // number
@categoryInfer Types InferSuccess <typeof const findUser: (id: string) => Result.ResultAsync<{
id: string;
name: string;
}, "NotFound">
findUser >;
// Type: { id: string; name: string }
type type FindUserError = "NotFound" FindUserError = import Result Result .type InferFailure<T> = [T] extends [(...args: any[]) => Result.ResultMaybeAsync<any, infer U>] ? U : [T] extends [Result.ResultMaybeAsync<any, infer U>] ? U : neverInfers the
Failure
value type E from a Result or a function returning a Result.
@typeParamT - A ResultMaybeAsync type or a function returning it.@exampleFrom a result object
import { Result } from '@praha/byethrow';
type R = Result.Result<number, string>;
type ErrorValue = Result.InferFailure<R>; // string
@exampleFrom a function
import { Result } from '@praha/byethrow';
const fn = () => Promise.resolve({ type: 'Failure', error: new Error() } as const);
type ErrorValue = Result.InferFailure<typeof fn>; // Error
@categoryInfer Types InferFailure <typeof const findUser: (id: string) => Result.ResultAsync<{
id: string;
name: string;
}, "NotFound">
findUser >;
// Type: 'NotFound'#References
| API | Purpose |
|---|---|
| Success<T> | Represents a successful result |
| Failure<E> | Represents a failed result |
| Result<T, E> | A union of Success and Failure |
| ResultAsync<T, E> | An alias for Promise<Result<T, E>> |
| ResultMaybeAsync<T, E> | Either a Result or a ResultAsync |
| ResultFor<R, T, E> | Result or ResultAsync, depending on whether R is async |
| InferSuccess<T> | Extracts the success type |
| InferFailure<T> | Extracts the error type |
