#Namespace: Result
Re-exports core Result-handling utilities under two convenient namespaces:
Result: Verbose and explicit usageR: Shorthand alias for more concise code
#Examples
Basic Usage
import { import Result Result } from '@praha/byethrow';
const const validateId: (id: string) => Result.Failure<Error> | Result.Success<void> 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(): Result.Result<void, 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 const findUser: (id: string) => Result.Result<{
id: string;
name: string;
}, Error>
findUser = import Result Result .function fn<(id: string) => {
id: string;
name: string;
}, Error>(options: {
try: (id: string) => {
id: string;
name: string;
};
catch: (error: unknown) => Error;
}): (id: string) => Result.Result<{
id: string;
name: string;
}, 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) => {
id: string;
name: string;
}
try : (id: string id : string) => {
return { id: string id , name: string name : 'John Doe' };
},
catch: (error: unknown) => Error catch : (error: unknown error ) => new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error ('Failed to find user', { ErrorOptions.cause?: unknown cause : error: unknown error }),
});
const const result: Result.Result<{
id: string;
name: string;
}, Error>
result = import Result Result .function pipe<Result.Result<"u123", never>, Result.Result<"u123", Error>, Result.Result<{
id: string;
name: string;
}, Error>>(a: Result.Result<"u123", never>, ab: (a: Result.Result<"u123", never>) => Result.Result<"u123", Error>, bc: (b: Result.Result<"u123", Error>) => Result.Result<{
id: string;
name: string;
}, Error>): Result.Result<{
id: string;
name: string;
}, Error> (+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 andThrough<Result.Result<"u123", never>, Result.Failure<Error> | Result.Success<void>>(fn: (a: "u123") => Result.Failure<Error> | Result.Success<void>): (result: Result.Result<"u123", never>) => Result.Result<"u123", Error> (+1 overload)Runs an additional computation using the success value of a
Result
or
ResultAsync
,
but returns the original result if the additional computation is successful.
If either the original result or the side effect result is a
Failure
, that failure is returned.
Useful for running validations or side effects without altering the main result on success.
@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(5),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Success', value: 5 }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(-10),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Failure', error: 'Must be > 0' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThrough (const validateId: (id: string) => Result.Failure<Error> | Result.Success<void> validateId ),
import Result Result .function andThen<Result.Result<"u123", Error>, Result.Result<{
id: string;
name: string;
}, Error>>(fn: (a: "u123") => Result.Result<{
id: string;
name: string;
}, Error>): (result: Result.Result<"u123", Error>) => Result.Result<{
id: string;
name: 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 findUser: (id: string) => Result.Result<{
id: string;
name: string;
}, Error>
findUser ),
);
if (import Result Result .function isSuccess<Result.Result<{
id: string;
name: string;
}, Error>>(result: Result.Result<{
id: string;
name: string;
}, Error>): result is Result.Success<{
id: string;
name: string;
}>
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<{
id: string;
name: string;
}, 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<{
id: string;
name: string;
}>
result .value: {
id: string;
name: string;
}
value ); // User found: John Doe
}Shorthand Usage
import { import R R } from '@praha/byethrow';
const const validateId: (id: string) => R.Failure<Error> | R.Success<void> 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 R R .function fail<Error>(error: Error): R.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 R R .function succeed(): R.Result<void, 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 const findUser: (id: string) => R.Result<{
id: string;
name: string;
}, Error>
findUser = import R R .function fn<(id: string) => {
id: string;
name: string;
}, Error>(options: {
try: (id: string) => {
id: string;
name: string;
};
catch: (error: unknown) => Error;
}): (id: string) => R.Result<{
id: string;
name: string;
}, 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) => {
id: string;
name: string;
}
try : (id: string id : string) => {
return { id: string id , name: string name : 'John Doe' };
},
catch: (error: unknown) => Error catch : (error: unknown error ) => new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error ('Failed to find user', { ErrorOptions.cause?: unknown cause : error: unknown error }),
});
const const result: R.Result<{
id: string;
name: string;
}, Error>
result = import R R .function pipe<R.Result<"u123", never>, R.Result<"u123", Error>, R.Result<{
id: string;
name: string;
}, Error>>(a: R.Result<"u123", never>, ab: (a: R.Result<"u123", never>) => R.Result<"u123", Error>, bc: (b: R.Result<"u123", Error>) => R.Result<{
id: string;
name: string;
}, Error>): R.Result<{
id: string;
name: string;
}, Error> (+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 R R .function succeed<"u123">(value: "u123"): R.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 R R .function andThrough<R.Result<"u123", never>, R.Failure<Error> | R.Success<void>>(fn: (a: "u123") => R.Failure<Error> | R.Success<void>): (result: R.Result<"u123", never>) => R.Result<"u123", Error> (+1 overload)Runs an additional computation using the success value of a
Result
or
ResultAsync
,
but returns the original result if the additional computation is successful.
If either the original result or the side effect result is a
Failure
, that failure is returned.
Useful for running validations or side effects without altering the main result on success.
@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(5),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Success', value: 5 }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(-10),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Failure', error: 'Must be > 0' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThrough (const validateId: (id: string) => R.Failure<Error> | R.Success<void> validateId ),
import R R .function andThen<R.Result<"u123", Error>, R.Result<{
id: string;
name: string;
}, Error>>(fn: (a: "u123") => R.Result<{
id: string;
name: string;
}, Error>): (result: R.Result<"u123", Error>) => R.Result<{
id: string;
name: 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 findUser: (id: string) => R.Result<{
id: string;
name: string;
}, Error>
findUser ),
);
if (import R R .function isSuccess<R.Result<{
id: string;
name: string;
}, Error>>(result: R.Result<{
id: string;
name: string;
}, Error>): result is R.Success<{
id: string;
name: string;
}>
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: R.Result<{
id: string;
name: string;
}, Error>
result )) {
var console: Console console .Console.log(...data: any[]): voidThe console.log() static method outputs a message to the console.
log (const result: R.Success<{
id: string;
name: string;
}>
result .value: {
id: string;
name: string;
}
value ); // User found: John Doe
}#Core Types
| Type Alias | Description |
|---|---|
| Failure | Represents a failed result. |
| Result | A union type representing either a success or a failure. |
| ResultAsync | An asynchronous variant of Result, wrapped in a Promise. |
| ResultFor | Resolves to the appropriate Result type (sync or async) based on the input type. |
| ResultMaybeAsync | A result that may be either synchronous or asynchronous. |
| Success | Represents a successful result. |
#Infer Types
| Type Alias | Description |
|---|---|
| InferFailure | Infers the Failure value type E from a Result or a function returning a Result. |
| InferSuccess | Infers the Success value type T from a Result or a function returning a Result. |
#Creators
| Function | Description |
|---|---|
| do | Alias for succeed({}). Commonly used as a neutral base value in functional chains or monadic pipelines. |
| fail | Creates a Failure result from a given error. |
| fn | Wraps a function that may throw and returns a new function that returns a Result or ResultAsync. |
| succeed | Creates a Success result from a given value. |
| try | Executes a function that may throw and wraps the result in a Result or ResultAsync. |
#Combinators
| Function | Description |
|---|---|
| andThen | 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. |
| andThrough | Runs an additional computation using the success value of a Result or ResultAsync, but returns the original result if the additional computation is successful. |
| bind | Chains another Result-producing computation and merges its success value into the existing object under the specified key. |
| inspect | Executes a side effect function on the success value of a Result or ResultAsync, without modifying the original result. This is useful for debugging, logging, or performing other side effects while maintaining the original value and error state. |
| inspectError | Executes a side effect function on the error value of a Result or ResultAsync, without modifying the original result. This is useful for debugging, logging, or performing other side effects while maintaining the original value and error state. |
| let | Computes a plain value from the current success object and attaches it to the existing object under the specified key. |
| map | Applies a transformation function to the success value of a Result or ResultAsync. If the input is a Failure, it will be returned unchanged. |
| mapError | Applies a transformation function to the error value of a Result or ResultAsync. If the input is a Success, it will be returned unchanged. |
| orElse | 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. |
| orThrough | Runs an additional computation using the error value of a Result or ResultAsync, but returns the original failure if the additional computation is successful. |
#Unwraps
| Function | Description |
|---|---|
| unwrap | Extracts the success value from a Result or ResultAsync. |
| unwrapError | Extracts the error value from a Result or ResultAsync. |
#Assertions
| Function | Description |
|---|---|
| assertFailure | Asserts that a Result or ResultAsync is a Failure and returns it. This function requires that the result's success type is never, meaning the result is guaranteed to be a Failure at the type level. If the result is a Success at runtime, throws an error. |
| assertSuccess | Asserts that a Result or ResultAsync is a Success and returns it. This function requires that the result's error type is never, meaning the result is guaranteed to be a Success at the type level. If the result is a Failure at runtime, throws an error. |
#Type Guards
| Function | Description |
|---|---|
| isFailure | Type guard to check if a Result is a Failure. |
| isResult | Type guard to check if a value is a Result. |
| isSuccess | Type guard to check if a Result is a Success. |
#Utilities
| Function | Description |
|---|---|
| collect | Processes multiple Result or ResultAsync values into a single result. If all results are Success, returns a Success containing all values. If any result is a Failure, returns a Failure containing an array of all errors. |
| parse | Parses a value using a Standard Schema compatible schema. Returns a Result with the parsed value on success or validation errors on failure. |
| pipe | Applies a sequence of functions to a value, from left to right. |
| sequence | Processes multiple Result or ResultAsync values into a single result. If all results are Success, returns a Success containing all values. If any result is a Failure, immediately stops processing and returns a Failure with that single error. |
