logo
byethrow
Guide
Examples
API Reference
Guide
Examples
API Reference
logo
byethrow
@praha/byethrow

Modules

Result

Types

Type Alias: Failure<E>
Type Alias: InferFailure<T>
Type Alias: InferSuccess<T>
Type Alias: Result<T, E>
Type Alias: ResultAsync<T, E>
Type Alias: ResultFor<R, T, E>
Type Alias: ResultMaybeAsync<T, E>
Type Alias: Success<T>

Functions

Function: andThen()
Function: andThrough()
Function: assertFailure()
Function: assertSuccess()
Function: bind()
Function: combine()
Function: do()
Function: fail()
Function: inspect()
Function: inspectError()
Function: isFailure()
Function: isResult()
Function: isSuccess()
Function: map()
Function: mapError()
Function: orElse()
Function: parse()
Function: pipe()
Function: succeed()
Function: try()
Function: unwrap()
Function: unwrapError()

Last Updated:

Previous Page@praha/byethrow
Next PageType Alias: Failure<E>

#Result

Re-exports core Result-handling utilities under two convenient namespaces:

  • Result: Verbose and explicit usage
  • R: Shorthand alias for more concise code

#Examples

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): boolean

Returns 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
.
const fail: <Error>(error: Error) => Result.Result<never, Error> (+1 overload)
fail
(new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
('Invalid ID format'));
} return
import Result
Result
.
const succeed: () => Result.ResultFor<never, void, never> (+1 overload)
succeed
();
}; const
const findUser: (id: string) => Result.Result<{
    id: string;
    name: string;
}, Error>
findUser
=
import Result
Result
.
try<(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> (+7 overloads)
export try

Wraps a function execution (sync or async) or a Promise in a Result or ResultAsync type, capturing errors and returning them in a structured way.

You can use either a custom catch handler or rely on the safe: true option to assume the function cannot throw.

@function@typeParamT - The function type to execute (sync or async) or a Promise type.@typeParamE - The error type to return if catch is used.@example

Sync try-catch

import { Result } from '@praha/byethrow';

const fn = Result.try({
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>
@example

Sync try-catch with immediate execution

import { Result } from '@praha/byethrow';

const result = Result.try({
immediate: true,
try: () => {
const x = Math.random() * 10 - 5;
if (x < 0) throw new Error('Negative!');
return x * 2;
},
catch: (error) => new Error('Oops!', { cause: error }),
});

// result is Result<number, Error>
@example

Sync safe

import { Result } from '@praha/byethrow';

const fn = Result.try({
safe: true,
try: (x: number) => x + 1,
});

const result = fn(1); // Result.Result<number, never>
@example

Sync safe with immediate execution

import { Result } from '@praha/byethrow';

const result = Result.try({
safe: true,
immediate: true,
try: () => Math.random() + 1,
});

// result is Result<number, never>
@example

Async try-catch

import { Result } from '@praha/byethrow';

const fn = Result.try({
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>
@example

Async try-catch with immediate execution

import { Result } from '@praha/byethrow';

const result = Result.try({
immediate: true,
try: () => fetch('/api/data'),
catch: (error) => new Error('Fetch failed', { cause: error }),
});

// result is ResultAsync<Response, Error>
@example

Async safe

import { Result } from '@praha/byethrow';

const fn = Result.try({
safe: true,
try: async () => await Promise.resolve('ok'),
});

const result = await fn(); // Result.ResultAsync<string, never>
@example

Async safe with immediate execution

import { Result } from '@praha/byethrow';

const result = Result.try({
safe: true,
immediate: true,
try: () => Promise.resolve('ok'),
});

// result is ResultAsync<string, never>
@categoryCreators
try
({
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
.
const pipe: <Result.Result<string, never>, Result.Result<string, Error>, Result.Result<{
    id: string;
    name: string;
}, Error>>(a: Result.Result<string, never>, ab: (a: Result.Result<string, never>) => Result.Result<string, Error>, bc: (b: Result.Result<string, Error>) => Result.Result<{
    id: string;
    name: string;
}, Error>) => Result.Result<{
    id: string;
    name: string;
}, Error> (+25 overloads)
pipe
(
import Result
Result
.
const succeed: <string>(value: string) => Result.Result<string, never> (+1 overload)
succeed
('u123'),
import Result
Result
.
const andThrough: <Result.Result<string, never>, Result.Failure<Error> | Result.Success<void>>(fn: (a: string) => Result.Failure<Error> | Result.Success<void>) => (result: Result.Result<string, never>) => Result.Result<string, Error> (+1 overload)
andThrough
(
const validateId: (id: string) => Result.Failure<Error> | Result.Success<void>
validateId
),
import Result
Result
.
const andThen: <Result.Result<string, Error>, Result.Result<{
    id: string;
    name: string;
}, Error>>(fn: (a: string) => Result.Result<{
    id: string;
    name: string;
}, Error>) => (result: Result.Result<string, Error>) => Result.Result<{
    id: string;
    name: string;
}, Error> (+1 overload)
andThen
(
const findUser: (id: string) => Result.Result<{
    id: string;
    name: string;
}, Error>
findUser
),
); if (
import Result
Result
.
const isSuccess: <{
    id: string;
    name: string;
}>(result: Result.Result<{
    id: string;
    name: string;
}, unknown>) => result is Result.Success<{
    id: string;
    name: string;
}>

Type guard to check if a Result is a Success .

@function@typeParamT - The type of the success value.@paramresult - The Result to check.@returnstrue if the result is a Success, otherwise false.@example
import { 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

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.
Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0 .1.100
log
(
const result: Result.Success<{
    id: string;
    name: string;
}>
result
.
value: {
    id: string;
    name: string;
}
value
); // User found: John Doe
}
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): boolean

Returns 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
.
const fail: <Error>(error: Error) => R.Result<never, Error> (+1 overload)
fail
(new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
('Invalid ID format'));
} return
import R
R
.
const succeed: () => R.ResultFor<never, void, never> (+1 overload)
succeed
();
}; const
const findUser: (id: string) => R.Result<{
    id: string;
    name: string;
}, Error>
findUser
=
import R
R
.
try<(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> (+7 overloads)
export try

Wraps a function execution (sync or async) or a Promise in a Result or ResultAsync type, capturing errors and returning them in a structured way.

You can use either a custom catch handler or rely on the safe: true option to assume the function cannot throw.

@function@typeParamT - The function type to execute (sync or async) or a Promise type.@typeParamE - The error type to return if catch is used.@example

Sync try-catch

import { Result } from '@praha/byethrow';

const fn = Result.try({
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>
@example

Sync try-catch with immediate execution

import { Result } from '@praha/byethrow';

const result = Result.try({
immediate: true,
try: () => {
const x = Math.random() * 10 - 5;
if (x < 0) throw new Error('Negative!');
return x * 2;
},
catch: (error) => new Error('Oops!', { cause: error }),
});

// result is Result<number, Error>
@example

Sync safe

import { Result } from '@praha/byethrow';

const fn = Result.try({
safe: true,
try: (x: number) => x + 1,
});

const result = fn(1); // Result.Result<number, never>
@example

Sync safe with immediate execution

import { Result } from '@praha/byethrow';

const result = Result.try({
safe: true,
immediate: true,
try: () => Math.random() + 1,
});

// result is Result<number, never>
@example

Async try-catch

import { Result } from '@praha/byethrow';

const fn = Result.try({
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>
@example

Async try-catch with immediate execution

import { Result } from '@praha/byethrow';

const result = Result.try({
immediate: true,
try: () => fetch('/api/data'),
catch: (error) => new Error('Fetch failed', { cause: error }),
});

// result is ResultAsync<Response, Error>
@example

Async safe

import { Result } from '@praha/byethrow';

const fn = Result.try({
safe: true,
try: async () => await Promise.resolve('ok'),
});

const result = await fn(); // Result.ResultAsync<string, never>
@example

Async safe with immediate execution

import { Result } from '@praha/byethrow';

const result = Result.try({
safe: true,
immediate: true,
try: () => Promise.resolve('ok'),
});

// result is ResultAsync<string, never>
@categoryCreators
try
({
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
.
const pipe: <R.Result<string, never>, R.Result<string, Error>, R.Result<{
    id: string;
    name: string;
}, Error>>(a: R.Result<string, never>, ab: (a: R.Result<string, never>) => R.Result<string, Error>, bc: (b: R.Result<string, Error>) => R.Result<{
    id: string;
    name: string;
}, Error>) => R.Result<{
    id: string;
    name: string;
}, Error> (+25 overloads)
pipe
(
import R
R
.
const succeed: <string>(value: string) => R.Result<string, never> (+1 overload)
succeed
('u123'),
import R
R
.
const andThrough: <R.Result<string, never>, R.Failure<Error> | R.Success<void>>(fn: (a: string) => R.Failure<Error> | R.Success<void>) => (result: R.Result<string, never>) => R.Result<string, Error> (+1 overload)
andThrough
(
const validateId: (id: string) => R.Failure<Error> | R.Success<void>
validateId
),
import R
R
.
const andThen: <R.Result<string, Error>, R.Result<{
    id: string;
    name: string;
}, Error>>(fn: (a: string) => R.Result<{
    id: string;
    name: string;
}, Error>) => (result: R.Result<string, Error>) => R.Result<{
    id: string;
    name: string;
}, Error> (+1 overload)
andThen
(
const findUser: (id: string) => R.Result<{
    id: string;
    name: string;
}, Error>
findUser
),
); if (
import R
R
.
const isSuccess: <{
    id: string;
    name: string;
}>(result: R.Result<{
    id: string;
    name: string;
}, unknown>) => result is R.Success<{
    id: string;
    name: string;
}>

Type guard to check if a Result is a Success .

@function@typeParamT - The type of the success value.@paramresult - The Result to check.@returnstrue if the result is a Success, otherwise false.@example
import { 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

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
//   Error: Whoops, something bad happened
//     at [eval]:5:15
//     at Script.runInThisContext (node:vm:132:18)
//     at Object.runInThisContext (node:vm:309:38)
//     at node:internal/process/execution:77:19
//     at [eval]-wrapper:6:22
//     at evalScript (node:internal/process/execution:76:60)
//     at node:internal/main/eval_string:23:3

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);

myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err

const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
@seesource
console
.
Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0 .1.100
log
(
const result: R.Success<{
    id: string;
    name: string;
}>
result
.
value: {
    id: string;
    name: string;
}
value
); // User found: John Doe
}

#Core Types

Type AliasDescription
FailureRepresents a failed result.
ResultA union type representing either a success or a failure.
ResultAsyncAn asynchronous variant of Result, wrapped in a Promise.
ResultForResolves to the appropriate Result type (sync or async) based on the input type.
ResultMaybeAsyncA result that may be either synchronous or asynchronous.
SuccessRepresents a successful result.

#Infer Types

Type AliasDescription
InferFailureInfers the Failure value type E from a Result or a function returning a Result.
InferSuccessInfers the Success value type T from a Result or a function returning a Result.

#Creators

FunctionDescription
doAlias for succeed({}). Commonly used as a neutral base value in functional chains or monadic pipelines.
failCreates a Failure result from a given error. Automatically wraps the error in a Promise if it is asynchronous.
succeedCreates a Success result from a given value. Automatically wraps the value in a Promise if it is asynchronous.
tryWraps a function execution (sync or async) or a Promise in a Result or ResultAsync type, capturing errors and returning them in a structured way.

#Combinators

FunctionDescription
andThenChains 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.
andThroughRuns an additional computation using the success value of a Result or ResultAsync, but returns the original result if the additional computation is successful.
bindChains another Result-producing computation and merges its success value into the existing object under the specified key.
inspectExecutes 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.
inspectErrorExecutes 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.
mapApplies a transformation function to the success value of a Result or ResultAsync. If the input is a Failure, it will be returned unchanged.
mapErrorApplies a transformation function to the error value of a Result or ResultAsync. If the input is a Success, it will be returned unchanged.
orElseChains 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.

#Unwraps

FunctionDescription
unwrapExtracts the success value from a Result or ResultAsync.
unwrapErrorExtracts the error value from a Result or ResultAsync.

#Assertions

FunctionDescription
assertFailureAsserts that a Result or ResultAsync is a Failure and returns it. If the result is a Success, throws an error.
assertSuccessAsserts that a Result or ResultAsync is a Success and returns it. If the result is a Failure, throws an error.

#Type Guards

FunctionDescription
isFailureType guard to check if a Result is a Failure.
isResultType guard to check if a value is a Result.
isSuccessType guard to check if a Result is a Success.

#Utilities

FunctionDescription
combineCombines multiple Result or ResultAsync values into a single result. If all inputs are Success, returns a Success with combined values. If any input is a Failure, returns a Failure with an array of all errors.
parseParses a value using a Standard Schema compatible schema. Returns a Result with the parsed value on success or validation errors on failure.
pipeApplies a sequence of functions to a value, from left to right.