--- url: /byethrow/guide/start/introduction.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Introduction `@praha/byethrow` is a lightweight, tree-shakable library that brings the `Result` type to JavaScript and TypeScript. Instead of throwing exceptions, functions return a value that is either a success or a failure. The possibility of failure becomes part of the type, so the compiler can make sure it is handled. ## At a Glance With `throw`, a function's signature tells you nothing about how it can fail: ```ts // @noErrors type User = { id: string; name: string }; // ---cut-before--- // Can this throw? Which errors? The signature doesn't say. const findUser = async (id: string): Promise => { // ... }; ``` With byethrow, every expected failure appears in the return type, and results can be composed step by step without `try/catch`: ```ts type User = { id: string; name: string }; declare const db: { findUser: (id: string) => Promise }; class InvalidIdError extends Error { override readonly name = 'InvalidIdError'; } class UserNotFoundError extends Error { override readonly name = 'UserNotFoundError'; } // ---cut-before--- import { Result } from '@praha/byethrow'; const validateId = (id: string) => { if (!id.startsWith('u')) { return Result.fail(new InvalidIdError()); } return Result.succeed(id); }; const findUser = async (id: string): Result.ResultAsync => { const user = await db.findUser(id); if (!user) { return Result.fail(new UserNotFoundError()); } return Result.succeed(user); }; const result = await Result.pipe( Result.succeed('u123'), Result.andThen(validateId), Result.andThen(findUser), ); // Type: Result.Result ``` ## Features - **Tree-shakable**: Every function is an independent export, so your bundle only includes what you use. - **Plain objects**: A `Result` is a plain object, not a class instance. It is easy to log, serialize, and debug. - **One API for sync and async**: Every function accepts both `Result` and `Promise>`. - **Composable**: Build readable pipelines with `pipe` and combinators such as `map`, `andThen`, and `andThrough`. - **Focused**: A small set of Result-centric functions, without aliases or confusing variants. - **Fully type-safe**: Every function is covered by type tests, so success and error types are inferred precisely. ## When to Use byethrow byethrow works best for failures that are part of your application's normal behavior, such as: - **API calls** that can fail because of network or server errors - **Input validation** where you want to report one or all problems to the user - **File operations** that can fail because of missing files or permissions - **Parsers** that must reject invalid input gracefully - **Business rules** such as "the post has already been deleted" or "the user has no permission" You don't need to wrap every possible error in a `Result`. Truly unexpected errors, such as a lost database connection, can still be thrown and handled by your infrastructure. See [Result vs throw](/byethrow/guide/best-practices/result-vs-throw.md) for how to draw that line. ## Next Steps - [Why byethrow?](/byethrow/guide/start/why.md): The problems byethrow solves and how it compares to other approaches - [Quick Start](/byethrow/guide/start/quick.md): Install the package and write your first `Result`-based code - [Tutorial](/byethrow/guide/tutorial/basics/result-type.md): Learn every function step by step --- url: /byethrow/guide/start/why.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Why byethrow? This page explains the problems a `Result` type solves, and why byethrow in particular is a good fit for everyday TypeScript projects. ## The Problem with `try/catch` JavaScript lets any function throw at any time, and TypeScript cannot describe what a function throws. This leads to several problems: - **Invisible failures**: Nothing in a function's signature tells you that it can fail, so it is easy to forget to handle an error. - **Untyped errors**: The value caught in a `catch` block is always `unknown`, so you have to guess what it is. - **Tangled control flow**: `try/catch` blocks mix error handling with business logic and make the happy path harder to follow. A `Result` type solves these problems by treating failures as ordinary return values: - **Explicit**: Failures are part of the return type, so the compiler reminds you to handle them. - **Typed**: Each error keeps its exact type, all the way to the place where it is handled. - **Composable**: Operations can be chained, and a failure automatically skips the remaining steps. - **Separated**: Business logic reads as a straight line, and error handling happens in one place. ## Why byethrow Over Other Libraries? There are several excellent Result libraries in the TypeScript ecosystem. byethrow aims for the sweet spot between a minimal utility and a full functional programming framework. ### Compared to neverthrow neverthrow represents results as class instances with methods, and provides separate `Result` and `ResultAsync` classes. byethrow makes different trade-offs: - **Plain objects**: A byethrow `Result` is a plain `{ type, value }` or `{ type, error }` object that can be logged, serialized, and compared as it is. - **Standalone functions**: Operations are independent functions combined with `pipe`, so unused ones are removed by tree-shaking. - **One API for sync and async**: The same functions work with both `Result` and `Promise`, so you never need to convert between two kinds of results. - **More building blocks**: Functions such as `bind` for building objects, `collect` for gathering every error, and `parse` for [Standard Schema](https://standardschema.dev/) validation cover common real-world needs. ### Compared to Effect and fp-ts Effect and fp-ts are extremely powerful, but they come with their own runtime model and a large vocabulary of functional programming concepts. byethrow only deals with success and failure, so your team can adopt it without learning a new programming paradigm. ## Designed for Real-World Use - **Team-friendly**: Adopt it one function at a time. It works alongside existing code that throws. - **TypeScript-first**: Success and error types are inferred through every step of a pipeline. - **Lightweight**: A small runtime with full tree-shaking support. - **Predictable**: A consistent naming scheme (`map` / `mapError`, `andThen` / `orElse`, and so on) keeps the API easy to remember. - **Well-equipped**: A [linter plugin](/byethrow/guide/ecosystem/linter/index.md), [test matchers](/byethrow/guide/ecosystem/testing.md), and [documentation for AI assistants](/byethrow/guide/ecosystem/llm-integration.md) help the whole team follow the same patterns. --- url: /byethrow/guide/start/quick.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # 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: ```sh [npm] npm install @praha/byethrow ``` ```sh [yarn] yarn add @praha/byethrow ``` ```sh [pnpm] pnpm add @praha/byethrow ``` ```sh [bun] bun add @praha/byethrow ``` ```sh [deno] deno 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: ```ts import { Result } from '@praha/byethrow'; const divide = (a: number, b: number) => { if (b === 0) { return Result.fail(new Error('Cannot divide by zero')); } return Result.succeed(a / 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: ```ts import { Result } from '@praha/byethrow'; declare const divide: (a: number, b: number) => Result.Result; // ---cut-before--- const result = divide(10, 2); if (Result.isSuccess(result)) { console.log(result.value); // 5 } else { console.error(result.error.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: ```ts import { Result } from '@praha/byethrow'; const parseJson = Result.fn({ try: (text: string) => JSON.parse(text) as unknown, catch: (error) => new Error('Invalid JSON', { cause: error }), }); parseJson('{"name": "Alice"}'); // { type: 'Success', value: { name: 'Alice' } } 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: ```ts import { Result } from '@praha/byethrow'; const validateId = (id: string) => { if (!id.startsWith('u')) { return Result.fail(new Error('Invalid ID format')); } return Result.succeed(id); }; const findUser = (id: string) => { if (id !== 'u123') { return Result.fail(new Error('User not found')); } return Result.succeed({ id, name: 'John Doe' }); }; const welcome = (id: string) => Result.pipe( Result.succeed(id), Result.andThen(validateId), Result.andThen(findUser), Result.map((user) => `Welcome, ${user.name}!`), ); welcome('u123'); // { type: 'Success', value: 'Welcome, John Doe!' } 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)`: creates `Success` - `Result.andThen(validateId)`: runs on `Success` and returns `Success` or `Failure` - `Result.andThen(findUser)`: runs on `Success` and returns `Success` or `Failure` - `Result.map(toWelcomeMessage)`: runs on `Success` and returns `Success` ## Recovering from Failures Use `Result.orElse` to handle a failure and continue with a fallback: ```ts import { Result } from '@praha/byethrow'; declare const welcome: (id: string) => Result.Result; // ---cut-before--- const result = Result.pipe( welcome('x999'), Result.orElse(() => Result.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: ```ts import { Result } from '@praha/byethrow'; type User = { id: string; name: string }; declare const validateId: (id: string) => Result.Result; // ---cut-before--- const fetchUser = Result.fn({ try: async (id: string) => { const response = await fetch(`/api/users/${id}`); return await response.json() as User; }, catch: (error) => new Error('Failed to fetch user', { cause: error }), }); const result = await Result.pipe( Result.succeed('u123'), Result.andThen(validateId), // sync Result.andThen(fetchUser), // async Result.map((user) => user.name), ); // Type: Result.Result ``` ## Next Steps - [Tutorial](/byethrow/guide/tutorial/basics/result-type.md): Learn every function in depth, step by step. - [Custom Error](/byethrow/guide/best-practices/custom-error.md): Replace generic `Error` objects with specific error types. - [Linter Plugin](/byethrow/guide/ecosystem/linter/index.md) and [Testing](/byethrow/guide/ecosystem/testing.md): Keep your codebase consistent and your tests expressive. - [Examples](/byethrow/examples/parse-package-json.md): See byethrow in complete, runnable projects. --- url: /byethrow/guide/tutorial/basics/result-type.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # 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: ```ts import { Result } from '@praha/byethrow'; // A Success holds a value const success: Result.Success = { type: 'Success', value: 42, }; // A Failure holds an error const failure: Result.Failure = { type: 'Failure', 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` is the union of `Success` and `Failure`. `T` is the type of the success value, and `E` is the type of the error: ```ts import { Result } from '@praha/byethrow'; // Returns either a Success or a Failure const divide = (a: number, b: number): Result.Result => { if (b === 0) { return { type: 'Failure', error: 'Cannot divide by zero' }; } return { type: 'Success', value: a / b }; }; const result = divide(10, 2); // Type: Result.Result ``` ## 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: ```ts // @noErrors type Config = { host: string; port: number }; // ---cut-before--- // ❌ Does this throw? We can't tell from the signature const parseConfig = (path: string): Config => { // ... } ``` With `Result`, the return type makes it clear: ```ts // @noErrors import { Result } from '@praha/byethrow'; type Config = { host: string; port: number }; class ParseError extends Error {} // ---cut-before--- // ✅ The return type tells us this might fail, and how const parseConfig = (path: string): Result.Result => { // ... } ``` ### 2. Errors Keep Their Types A caught exception is always `unknown`. A `Result` preserves the exact error type: ```ts import { Result } from '@praha/byethrow'; type ValidationError = { field: string; message: string }; const validateEmail = (email: string): Result.Result => { if (!email.includes('@')) { return Result.fail({ field: 'email', message: 'Invalid email format' }); } return Result.succeed(email); }; const result = validateEmail('test'); if (Result.isFailure(result)) { // TypeScript knows result.error is ValidationError console.log(`Error in ${result.error.field}: ${result.error.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](/byethrow/guide/tutorial/chaining/pipe-basics.md) chapter: ```ts // @filename: type.ts export type User = { id: string; name: string; }; // @filename: functions.ts import { Result } from '@praha/byethrow'; import type { User } from './type'; class ValidationError extends Error {} export declare const validate: (value: User) => Result.Result; class TransformError extends Error {} export declare const transform: (value: User) => Result.Result; class SaveError extends Error {} export declare const save: (value: User) => Result.ResultAsync; // @filename: index.ts import { validate, transform, save } from './functions'; const input = { id: '', name: '' }; // ---cut-before--- import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.succeed(input), Result.andThen(validate), Result.andThen(transform), Result.andThen(save), ); // Type: Result.ResultAsync ``` ## Async Results An asynchronous `Result` is represented by `ResultAsync`, which is simply an alias for `Promise>`: ```ts import { Result } from '@praha/byethrow'; const asyncResult: Result.ResultAsync = Promise.resolve(Result.succeed(42)); // Type: Result.ResultAsync // Since ResultAsync is just a Promise, you can await it const resolved = await asyncResult; // Type: Result.Result ``` ### 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: ```ts import { Result } from '@praha/byethrow'; // Sync function const validate = (input: string): Result.Result => { if (input.length === 0) { return Result.fail(new Error('Input is empty')); } return Result.succeed(input); }; // Async function const fetchData = async (input: string): Result.ResultAsync => { // Simulating an API call return Result.succeed(input.length); }; const result = Result.pipe( Result.succeed('hello'), Result.andThen(validate), // sync Result.andThen(fetchData), // async: the pipeline becomes async from here Result.andThen((n) => Result.succeed(n * 2)), // sync, but runs in the async pipeline ); // Type: Result.ResultAsync ``` ## Utility Types The library also provides a few types that help when writing your own functions around `Result`. ### `ResultMaybeAsync` `ResultMaybeAsync` is either a `Result` or a `ResultAsync`. It is useful when an implementation may be either synchronous or asynchronous: ```ts import { Result } from '@praha/byethrow'; type User = { id: string; name: string }; type UserRepository = { // Both sync (e.g. in-memory) and async (e.g. database) implementations are allowed findById: (id: string) => Result.ResultMaybeAsync; }; ``` ### `InferSuccess` and `InferFailure` `InferSuccess` and `InferFailure` extract the success and error types from a `Result` type, or from a function that returns one: ```ts import { Result } from '@praha/byethrow'; declare const findUser: (id: string) => Result.ResultAsync<{ id: string; name: string }, 'NotFound'>; type User = Result.InferSuccess; // Type: { id: string; name: string } type FindUserError = Result.InferFailure; // Type: 'NotFound' ``` ## References | API | Purpose | | ------------------------------------------------------------------------- | ------------------------------------------------------------ | | [Success\](/byethrow/api/types/Result.Success.md) | Represents a successful result | | [Failure\](/byethrow/api/types/Result.Failure.md) | Represents a failed result | | [Result\](/byethrow/api/types/Result.Result.md) | A union of `Success` and `Failure` | | [ResultAsync\](/byethrow/api/types/Result.ResultAsync.md) | An alias for `Promise>` | | [ResultMaybeAsync\](/byethrow/api/types/Result.ResultMaybeAsync.md) | Either a `Result` or a `ResultAsync` | | [ResultFor\](/byethrow/api/types/Result.ResultFor.md) | `Result` or `ResultAsync`, depending on whether `R` is async | | [InferSuccess\](/byethrow/api/types/Result.InferSuccess.md) | Extracts the success type | | [InferFailure\](/byethrow/api/types/Result.InferFailure.md) | Extracts the error type | --- url: /byethrow/guide/tutorial/basics/creating-results.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Creating Results Now that you know what a `Result` looks like, let's create them with the library's helper functions. ## Creating a Success with `succeed` `succeed` creates a `Success` result: ```ts import { Result } from '@praha/byethrow'; // With a value const success = Result.succeed(42); // Type: Result.Result<42, never> // Without a value (void) const voidSuccess = Result.succeed(); // Type: Result.Result ``` The error type is `never` because this result can never be a failure. A `void` success is handy for operations that have no meaningful return value, such as saving or deleting something. ## Creating a Failure with `fail` `fail` creates a `Failure` result: ```ts import { Result } from '@praha/byethrow'; // With an error value const failure = Result.fail('NotFound'); // Type: Result.Result // Without a value (void) const voidFailure = Result.fail(); // Type: Result.Result ``` Any value can be used as an error. In real applications, we recommend using dedicated error classes, as described in [Custom Error](/byethrow/guide/best-practices/custom-error.md). :::info As the examples above show, `succeed` and `fail` keep literal types such as `42` and `'NotFound'` instead of widening them to `number` and `string`. This makes string literal errors like `'NotFound'` easy to distinguish from one another. When you want a wider type, annotate the return type of your function, as shown below. ::: ## Returning Results from Functions The most common way to use `succeed` and `fail` is to return them from your own functions, in place of `return` and `throw`: ```ts import { Result } from '@praha/byethrow'; const parseAge = (input: string) => { const age = Number(input); if (!Number.isInteger(age) || age < 0) { return Result.fail('InvalidAge'); } return Result.succeed(age); }; const result = parseAge('20'); // Type: Result.Result ``` TypeScript infers both the success type and the error type from the `return` statements. You can also annotate the return type explicitly, which is a good practice for exported functions: ```ts import { Result } from '@praha/byethrow'; const parseAge = (input: string): Result.Result => { const age = Number(input); if (!Number.isInteger(age) || age < 0) { return Result.fail(`Invalid age: ${input}`); } return Result.succeed(age); }; ``` :::info `succeed` and `fail` do not await a `Promise` for you. If you have an async value, await it first, or use an `async` function whose return type is `ResultAsync`: ```ts import { Result } from '@praha/byethrow'; declare const loadName: () => Promise; // ---cut-before--- const getName = async (): Result.ResultAsync => { const name = await loadName(); return Result.succeed(name); }; ``` ::: ## Starting a Pipeline with `do` `do` creates a `Success` that holds an empty object: ```ts import { Result } from '@praha/byethrow'; const start = Result.do(); // Type: Result.Result<{}, never> ``` It is the starting point for building up an object step by step with `bind`, which is covered in [Building Objects](/byethrow/guide/tutorial/combining/building-objects.md): ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.do(), Result.bind('name', () => Result.succeed('Alice')), Result.bind('age', () => Result.succeed(30)), ); // { type: 'Success', value: { name: 'Alice', age: 30 } } ``` ## References | API | Purpose | | ----------------------------------------------------------- | ----------------------------------------------- | | [succeed(value)](/byethrow/api/functions/Result.succeed.md) | Create a success result | | [fail(error)](/byethrow/api/functions/Result.fail.md) | Create a failure result | | [do()](/byethrow/api/functions/Result.do.md) | Create a success result holding an empty object | --- url: /byethrow/guide/tutorial/basics/checking-results.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Checking Results Before you can read the contents of a `Result`, you need to know whether it is a success or a failure. This page covers the type guard functions that check a `Result` and narrow its type. ## Checking for Success with `isSuccess` `isSuccess` returns `true` if the `Result` is a `Success`. Inside the `if` block, TypeScript narrows the type so that you can safely access `value`: ```ts import { Result } from '@praha/byethrow'; const result: Result.Result = Result.succeed(42); if (Result.isSuccess(result)) { // result is narrowed to Success console.log(result.value); // 42 } ``` Narrowing also works for the other branch. If the result is not a `Success`, it must be a `Failure`, so `error` is available there: ```ts import { Result } from '@praha/byethrow'; const describe = (result: Result.Result) => { if (Result.isSuccess(result)) { // ✅ `value` is available here return result.value.toUpperCase(); } // ✅ `error` is available here return `Error: ${result.error.message}`; }; ``` ## Checking for Failure with `isFailure` `isFailure` is the counterpart of `isSuccess`. It returns `true` if the `Result` is a `Failure`: ```ts import { Result } from '@praha/byethrow'; const result: Result.Result = Result.fail('Something went wrong'); if (Result.isFailure(result)) { // result is narrowed to Failure console.log(result.error); // "Something went wrong" } ``` ### Early Return A common pattern is to handle the failure first and return early. After the `if` block, the result is known to be a `Success`: ```ts type User = { id: number; name: string }; // ---cut-before--- import { Result } from '@praha/byethrow'; const getUserName = (result: Result.Result) => { if (Result.isFailure(result)) { console.error('Failed to find user:', result.error); return null; } // result is narrowed to Success return result.value.name; }; ``` :::tip Prefer `Result.isFailure(result)` over `!Result.isSuccess(result)`, and vice versa. The [no-negated-type-guards](/byethrow/guide/ecosystem/linter/no-negated-type-guards.md) lint rule enforces this automatically. ::: ## Checking Whether a Value Is a Result with `isResult` `isResult` checks whether an arbitrary value is a `Result` at all. This is useful when you receive a value of an unknown type: ```ts import { Result } from '@praha/byethrow'; const stringify = (value: unknown): string => { if (Result.isResult(value)) { // value is narrowed to Result if (Result.isSuccess(value)) { return `Success: ${JSON.stringify(value.value)}`; } return `Failure: ${JSON.stringify(value.error)}`; } return JSON.stringify(value); }; ``` ## References | API | Purpose | | ---------------------------------------------------------------- | ----------------------------------- | | [isSuccess(result)](/byethrow/api/functions/Result.isSuccess.md) | Check whether a Result is a Success | | [isFailure(result)](/byethrow/api/functions/Result.isFailure.md) | Check whether a Result is a Failure | | [isResult(value)](/byethrow/api/functions/Result.isResult.md) | Check whether a value is a Result | --- url: /byethrow/guide/tutorial/basics/wrapping-functions.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Wrapping Functions Third-party libraries, built-in APIs such as `JSON.parse`, and legacy code often throw exceptions. `fn` and `try` wrap such code and convert thrown exceptions into `Failure` results. ## Creating Reusable Wrappers with `fn` - `a`: `try(...args)` returns `a` → `Success(a)` - `throw x`: `catch(x)` returns `e` → `Failure(e)` `fn` takes a potentially throwing function and returns a new function that returns a `Result` instead: ```ts import { Result } from '@praha/byethrow'; const parseJson = Result.fn({ try: (input: string) => JSON.parse(input) as unknown, catch: (error) => new Error('Invalid JSON', { cause: error }), }); const result = parseJson('{"name": "Alice"}'); // Type: Result.Result ``` It takes two options: - `try`: The function to wrap. The wrapped function accepts the same arguments. - `catch`: Converts the thrown value into your error type. The thrown value is `unknown`, so pass it as `cause` to keep the original error. If `try` returns normally, its return value becomes a `Success`. If it throws, the value returned by `catch` becomes a `Failure`. ### Async Functions If `try` returns a `Promise`, the wrapped function returns a `ResultAsync`. A rejected promise is converted into a `Failure` in the same way as a thrown exception: ```ts import { Result } from '@praha/byethrow'; type User = { id: string; name: string }; const fetchUser = Result.fn({ try: async (id: string) => { const response = await fetch(`/api/users/${id}`); return await response.json() as User; }, catch: (error) => new Error('Failed to fetch user', { cause: error }), }); const result = await fetchUser('u123'); // Type: Result.Result ``` :::tip Use `try` only to wrap code that throws on its own. Don't `throw` inside it yourself to signal an expected failure, such as a non-OK HTTP status. Instead, chain a step that returns `Result.fail`, as shown in [Chaining Results](/byethrow/guide/tutorial/chaining/chaining-results.md). The [no-throw-in-callback](/byethrow/guide/ecosystem/linter/no-throw-in-callback.md) lint rule detects this mistake. ::: ## Running Code Once with `try` `try` runs a function immediately and returns its outcome as a `Result`. It is convenient when you only need to run the code once, in place: ```ts import { Result } from '@praha/byethrow'; const result = Result.try({ try: () => JSON.parse('{"name": "Alice"}') as { name: string }, catch: (error) => new Error('Invalid JSON', { cause: error }), }); // Type: Result.Result<{ name: string }, Error> ``` The options are the same as for `fn`, except that the `try` function takes no arguments. Async functions are supported as well, and return a `ResultAsync`: ```ts import { Result } from '@praha/byethrow'; const result = await Result.try({ try: () => fetch('/api/health'), catch: (error) => new Error('Health check failed', { cause: error }), }); // Type: Result.Result ``` ## Choosing Between `fn` and `try` | Scenario | Function to use | | --------------------------------------------------- | --------------- | | Define a reusable function, possibly with arguments | `fn` | | Run the code once, right where you need it | `try` | For example, use `fn` for a utility called from many places, and `try` for a one-off operation such as reading configuration at startup: ```ts class ParseError extends Error {} type Config = { name: string }; declare const configText: string; // ---cut-before--- import { Result } from '@praha/byethrow'; // A reusable JSON parser const parseJson = Result.fn({ try: (input: string) => JSON.parse(input) as unknown, catch: (error) => new ParseError('Invalid JSON', { cause: error }), }); // Reading the configuration once at startup const config = Result.try({ try: () => JSON.parse(configText) as Config, catch: (error) => new ParseError('Invalid config', { cause: error }), }); ``` ## Functions That Never Throw: the `safe` Option If a function is known not to throw, pass `safe: true` instead of `catch`. The error type becomes `never`: ```ts import { Result } from '@praha/byethrow'; const double = Result.fn({ safe: true, try: (x: number) => x * 2, }); const result = double(5); // Type: Result.Result ``` This is useful for turning a plain function into one that fits into a `Result` pipeline. `try` accepts the same option. :::warning With `safe: true`, exceptions are not caught. If the function does throw (or its promise rejects), the exception propagates to the caller as usual. Only use this option when you are sure the function cannot fail. ::: ## References | API | Purpose | | ----------------------------------------------------- | --------------------------------------------------------- | | [fn(options)](/byethrow/api/functions/Result.fn.md) | Wrap a throwing function into a function returning Result | | [try(options)](/byethrow/api/functions/Result.try.md) | Run a throwing function once and return a Result | --- url: /byethrow/guide/tutorial/basics/parsing-values.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Parsing Values Data that comes from outside your program, such as request bodies, JSON files, or environment variables, is `unknown` until it has been validated. `parse` validates such a value against a schema and returns the outcome as a `Result`. ## Validating with `parse` - `a`: the value matches the schema → `Success(a)` - `a`: the value does not match the schema → `Failure(issues)` `parse` accepts any schema that implements [Standard Schema](https://standardschema.dev/), the common interface supported by validation libraries such as [Zod](https://zod.dev/), [Valibot](https://valibot.dev/), and [ArkType](https://arktype.io/). The examples on this page use Zod: ```ts import { Result } from '@praha/byethrow'; import { z } from 'zod'; const User = z.object({ name: z.string().min(1), email: z.email(), }); const result = Result.parse(User, { name: 'Alice', email: 'alice@example.com' }); // Type: Result.Result<{ name: string; email: string }, ReadonlyArray> ``` If the value matches the schema, the result is a `Success` holding the parsed value, typed according to the schema. Otherwise, the result is a `Failure` holding the list of validation issues. ## Reading Validation Issues Each issue has a `message` and, optionally, a `path` pointing to the invalid property: ```ts import { Result } from '@praha/byethrow'; import { z } from 'zod'; const User = z.object({ name: z.string().min(1), email: z.email(), }); // ---cut-before--- const result = Result.parse(User, { name: '', email: 'not an email' }); if (Result.isFailure(result)) { for (const issue of result.error) { console.log(issue.path, issue.message); } } ``` ## Using `parse` in a Pipeline When called with only a schema, `parse` returns a function that validates its argument. This form fits naturally into a pipeline, which you will learn about in [Pipe Basics](/byethrow/guide/tutorial/chaining/pipe-basics.md): ```ts import { z } from 'zod'; const User = z.object({ name: z.string().min(1), email: z.email(), }); // ---cut-before--- import { Result } from '@praha/byethrow'; const parseJson = Result.fn({ try: (text: string) => JSON.parse(text) as unknown, catch: (error) => new Error('Invalid JSON', { cause: error }), }); const parseUser = (text: string) => Result.pipe( parseJson(text), Result.andThen(Result.parse(User)), ); ``` To replace the list of issues with your own error type, use [`mapError`](/byethrow/guide/tutorial/chaining/mapping-results.md): ```ts import { z } from 'zod'; const User = z.object({ name: z.string().min(1), email: z.email(), }); // ---cut-before--- import { Result } from '@praha/byethrow'; class ValidationError extends Error { override readonly name = 'ValidationError'; } const validateUser = (input: unknown) => Result.pipe( input, Result.parse(User), Result.mapError((issues) => new ValidationError('Invalid user', { cause: issues })), ); ``` :::warning `parse` only supports synchronous validation. If the schema performs asynchronous validation (for example, an async refinement), `parse` throws a `TypeError`. ::: ## References | API | Purpose | | --------------------------------------------------------------- | --------------------------------------- | | [parse(schema, value)](/byethrow/api/functions/Result.parse.md) | Validate a value with a Standard Schema | --- url: /byethrow/guide/tutorial/chaining/pipe-basics.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Pipe Basics `pipe` is the heart of `@praha/byethrow`. It connects multiple operations into a single, readable flow that runs from top to bottom. ## What Is `pipe`? `pipe` takes an initial value and passes it through a series of functions. Each function receives the output of the previous one: ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( 5, // Start with 5 (x) => x + 1, // 5 + 1 = 6 (x) => x * 2, // 6 * 2 = 12 (x) => `Result: ${x}`, // 'Result: 12' ); // 'Result: 12' ``` ## Why Use `pipe`? Without `pipe`, you either nest function calls, which must be read from the inside out: ```ts declare const add: (a: number, b: number) => number; declare const multiply: (a: number, b: number) => number; declare const format: (x: number) => string; // ---cut-before--- // ❌ Hard to read: inside out const result = format(multiply(add(5, 1), 2)); ``` Or you introduce intermediate variables, which is verbose: ```ts declare const add: (a: number, b: number) => number; declare const multiply: (a: number, b: number) => number; declare const format: (x: number) => string; // ---cut-before--- // ❌ Verbose: too many variables const step1 = add(5, 1); const step2 = multiply(step1, 2); const result = format(step2); ``` With `pipe`, the steps are listed in the order they run: ```ts declare const add: (a: number, b: number) => number; declare const multiply: (a: number, b: number) => number; declare const format: (x: number) => string; // ---cut-before--- import { Result } from '@praha/byethrow'; // ✅ Clear: top to bottom const result = Result.pipe( 5, (x) => add(x, 1), (x) => multiply(x, 2), format, ); ``` ## Using `pipe` with Results The real power of `pipe` shows when working with Results. Functions such as `Result.map` are curried: calling them with a callback returns a function that takes a `Result`, which is exactly what `pipe` expects: ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.succeed(10), Result.map((x) => x * 2), Result.map((x) => x + 5), ); // { type: 'Success', value: 25 } ``` ### Failures Short-Circuit the Pipeline Each function only runs its callback when the `Result` is in the state it cares about. For example, `map` only transforms a `Success`. Once a step fails, the following success-side steps are skipped and the `Failure` flows straight to the end: ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.succeed(10), Result.andThen((x) => x > 5 ? Result.fail('Too large') : Result.succeed(x)), Result.map((x) => x * 2), // Skipped Result.map((x) => x + 5), // Skipped ); // { type: 'Failure', error: 'Too large' } ``` This is why you don't need to check for errors after every step. - `Result.succeed(id)`: creates `Success` - `Result.andThen(validateId)`: runs on `Success` and returns `Success` or `Failure` - `Result.andThen(findUser)`: runs on `Success` and returns `Success` or `Failure` - `Result.map(toWelcomeMessage)`: runs on `Success` and returns `Success` - `Result.inspectError(console.error)`: runs on `Failure` and returns `Failure` ## Async Steps If any step returns a `Promise`, the rest of the pipeline runs asynchronously and `pipe` returns a `Promise`. You only need to `await` the final result: ```ts import { Result } from '@praha/byethrow'; type User = { id: string; name: string }; declare const fetchUser: (id: string) => Result.ResultAsync; // ---cut-before--- const result = await Result.pipe( Result.succeed('u123'), Result.andThen(fetchUser), // async Result.map((user) => user.name), // receives the resolved user ); // Type: Result.Result ``` ## Functions in This Chapter The following pages cover the functions you can use inside a pipeline. They come in pairs: one for the success side and one for the failure side. | What the callback does | On success | On failure | | -------------------------------------------------- | ---------------------------------------------------------------------- | --------------------------------------------------------------------- | | Transforms the value | [map](/byethrow/guide/tutorial/chaining/mapping-results.md) | [mapError](/byethrow/guide/tutorial/chaining/mapping-results.md) | | Returns the next `Result` | [andThen](/byethrow/guide/tutorial/chaining/chaining-results.md) | [orElse](/byethrow/guide/tutorial/chaining/chaining-results.md) | | Returns a `Result`, but the original value is kept | [andThrough](/byethrow/guide/tutorial/chaining/validation-recovery.md) | [orThrough](/byethrow/guide/tutorial/chaining/validation-recovery.md) | | Runs a side effect and its return value is ignored | [inspect](/byethrow/guide/tutorial/chaining/debugging.md) | [inspectError](/byethrow/guide/tutorial/chaining/debugging.md) | ## References | API | Purpose | | ------------------------------------------------------------- | ------------------------------------------ | | [pipe(value, ...fns)](/byethrow/api/functions/Result.pipe.md) | Pass a value through a series of functions | --- url: /byethrow/guide/tutorial/chaining/mapping-results.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Mapping Results `map` and `mapError` transform the contents of a `Result` without changing whether it is a `Success` or a `Failure`. ## Transforming Values with `map` - `Success(a)`: `fn(a)` returns `b` → `Success(b)` - `Failure(e)`: `fn` is not called → `Failure(e)` `map` transforms the success value with the given function. If the `Result` is a `Failure`, the function is not called and the `Failure` is returned as-is: ```ts import { Result } from '@praha/byethrow'; const success = Result.pipe( Result.succeed(2), Result.map((value) => value * 10), ); // { type: 'Success', value: 20 } const failure = Result.pipe( Result.fail('error'), Result.map((value) => value * 10), // Not called ); // { type: 'Failure', error: 'error' } ``` ### Example: Formatting Data for Display A common use of `map` is converting raw data into the shape your UI needs: ```ts declare const fetchProduct: (id: number) => Result.ResultAsync; // ---cut-before--- import { Result } from '@praha/byethrow'; type ProductRow = { id: number; name: string; priceInCents: number; }; type ProductView = { id: string; name: string; price: string; }; const toProductView = (product: ProductRow): ProductView => ({ id: String(product.id), name: product.name, price: `$${(product.priceInCents / 100).toFixed(2)}`, }); const getProductForDisplay = (id: number): Result.ResultAsync => { return Result.pipe( fetchProduct(id), Result.map(toProductView), ); }; ``` ## Transforming Errors with `mapError` - `Failure(e)`: `fn(e)` returns `f` → `Failure(f)` - `Success(a)`: `fn` is not called → `Success(a)` `mapError` is the counterpart of `map` for errors. It transforms the error value, and returns a `Success` as-is without calling the function: ```ts import { Result } from '@praha/byethrow'; const failure = Result.pipe( Result.fail('NotFound'), Result.mapError((error) => new Error(error)), ); // { type: 'Failure', error: Error('NotFound') } const success = Result.pipe( Result.succeed(123), Result.mapError((error) => new Error(error)), // Not called ); // { type: 'Success', value: 123 } ``` ### Example: Converting Domain Errors into HTTP Errors A common use of `mapError` is translating errors from one layer into the vocabulary of another, such as turning domain errors into HTTP responses: ```ts declare const processRequest: () => Result.ResultAsync<{ data: string }, DomainError>; // ---cut-before--- import { Result } from '@praha/byethrow'; type DomainError = | { type: 'NotFound'; resource: string } | { type: 'ValidationError'; field: string; message: string } | { type: 'Unauthorized' }; type HttpError = { status: number; body: { error: string; details?: string }; }; const toHttpError = (error: DomainError): HttpError => { switch (error.type) { case 'NotFound': return { status: 404, body: { error: 'Not Found', details: `${error.resource} was not found` }, }; case 'ValidationError': return { status: 400, body: { error: 'Bad Request', details: `${error.field}: ${error.message}` }, }; case 'Unauthorized': return { status: 401, body: { error: 'Unauthorized' }, }; } }; const handleRequest = (): Result.ResultAsync<{ data: string }, HttpError> => { return Result.pipe( processRequest(), Result.mapError(toHttpError), ); }; ``` ## Using `map` and `mapError` Together Both functions can be used in the same pipeline. Only one of them actually runs, depending on whether the result is a success or a failure: ```ts type UserRow = { id: number; first_name: string; last_name: string }; type UserView = { id: string; fullName: string }; type DatabaseError = 'RECORD_NOT_FOUND' | 'CONNECTION_FAILED'; type HttpError = { status: number; body: { error: string } }; declare const fetchUser: (id: number) => Result.ResultAsync; declare const toView: (row: UserRow) => UserView; declare const toHttpError: (error: DatabaseError) => HttpError; // ---cut-before--- import { Result } from '@praha/byethrow'; const getUserForView = (id: number): Result.ResultAsync => { return Result.pipe( fetchUser(id), Result.map(toView), // Runs only on success Result.mapError(toHttpError), // Runs only on failure ); }; ``` ## `map` or `andThen`? The function passed to `map` must return a plain value. If your function returns a `Result`, because the transformation itself can fail, use `andThen` instead, which is covered on the next page: ```ts declare const parseAge: (input: string) => Result.Result; // ---cut-before--- import { Result } from '@praha/byethrow'; // ❌ map wraps the returned Result in another Result const nested = Result.pipe( Result.succeed('20'), Result.map(parseAge), ); // Type: Result.Result, never> // ✅ andThen uses the returned Result as the next result const flat = Result.pipe( Result.succeed('20'), Result.andThen(parseAge), ); // Type: Result.Result ``` ## References | API | Purpose | | ---------------------------------------------------------- | --------------------------- | | [map(fn)](/byethrow/api/functions/Result.map.md) | Transform the success value | | [mapError(fn)](/byethrow/api/functions/Result.mapError.md) | Transform the error value | --- url: /byethrow/guide/tutorial/chaining/chaining-results.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Chaining Results `andThen` and `orElse` chain steps that themselves return a `Result`. While `map` and `mapError` only transform values, these functions let each step decide whether the pipeline continues as a success or a failure. ## Chaining Steps with `andThen` - `Success(a)`: `fn(a)` returns `Success(b)` → `Success(b)` - `Success(a)`: `fn(a)` returns `Failure(f)` → `Failure(f)` - `Failure(e)`: `fn` is not called → `Failure(e)` `andThen` calls the given function with the success value and returns the `Result` that the function returns. If the input is a `Failure`, the function is not called and the `Failure` is returned as-is: ```ts import { Result } from '@praha/byethrow'; // The function returns a Success const doubled = Result.pipe( Result.succeed(3), Result.andThen((value) => Result.succeed(value * 2)), ); // { type: 'Success', value: 6 } // The function returns a Failure const rejected = Result.pipe( Result.succeed(3), Result.andThen((value) => Result.fail(`Rejected: ${value}`)), ); // { type: 'Failure', error: 'Rejected: 3' } // The input is already a Failure const skipped = Result.pipe( Result.fail('error'), Result.andThen((value) => Result.succeed(value * 2)), // Not called ); // { type: 'Failure', error: 'error' } ``` The error type of the output is the union of the input's error type and the error type returned by the function. As you chain more steps, every possible error is tracked in the type. ### Example: Sequential Steps A typical use of `andThen` is running a sequence of steps, where each step uses the result of the previous one: ```ts import { Result } from '@praha/byethrow'; type User = { id: string; name: string; email: string }; declare const findUserById: (id: string) => Result.ResultAsync; declare const validateEmail: (user: User) => Result.Result; declare const saveUser: (user: User) => Result.ResultAsync; const result = await Result.pipe( Result.succeed('u123'), Result.andThen(findUserById), Result.andThen(validateEmail), Result.andThen(saveUser), ); // Type: Result.Result // If any step fails, the remaining steps are skipped ``` Error type after each step: - `Result.succeed('u123')`: `never` - `Result.andThen(findUserById)`: `'NotFound'` - `Result.andThen(validateEmail)`: `'NotFound' | 'InvalidEmail'` - `Result.andThen(saveUser)`: `'NotFound' | 'InvalidEmail' | 'SaveFailed'` ### Example: Rejecting Unexpected Values `andThen` is also the place to turn a value you don't accept into a `Failure`. For example, `fetch` does not throw on HTTP error statuses, so check the response in a separate step: ```ts import { Result } from '@praha/byethrow'; class NetworkError extends Error { override readonly name = 'NetworkError'; } class HttpError extends Error { override readonly name = 'HttpError'; } const request = Result.fn({ try: (url: string) => fetch(url), catch: (error) => new NetworkError('Request failed', { cause: error }), }); const result = await Result.pipe( request('/api/users/u123'), Result.andThen((response) => { if (!response.ok) { return Result.fail(new HttpError(`Unexpected status: ${response.status}`)); } return Result.succeed(response); }), ); // Type: Result.Result ``` ## Recovering with `orElse` - `Failure(e)`: `fn(e)` returns `Success(b)` → `Success(b)` - `Failure(e)`: `fn(e)` returns `Failure(f)` → `Failure(f)` - `Success(a)`: `fn` is not called → `Success(a)` `orElse` is the counterpart of `andThen` for failures. It calls the given function with the error value and returns the `Result` that the function returns. If the input is a `Success`, the function is not called: ```ts import { Result } from '@praha/byethrow'; // The function recovers with a Success const recovered = Result.pipe( Result.fail('original error'), Result.orElse(() => Result.succeed('default value')), ); // { type: 'Success', value: 'default value' } // The function returns a new Failure const replaced = Result.pipe( Result.fail('original error'), Result.orElse((error) => Result.fail(`New error: ${error}`)), ); // { type: 'Failure', error: 'New error: original error' } // The input is already a Success const untouched = Result.pipe( Result.succeed(42), Result.orElse(() => Result.succeed(0)), // Not called ); // { type: 'Success', value: 42 } ``` Unlike `andThen`, the original error type is replaced by the error type that the function returns. If the function always returns a `Success`, the error type becomes `never`. ### Example: Recovering from Specific Errors You don't have to recover from every error. Handle the errors you can, and return the others as they are: ```ts import { Result } from '@praha/byethrow'; type User = { id: string; name: string }; declare const findUser: (id: string) => Result.ResultAsync; const guest: User = { id: 'guest', name: 'Guest' }; const result = await Result.pipe( findUser('u123'), Result.orElse((error) => { if (error === 'NotFound') { return Result.succeed(guest); } return Result.fail(error); }), ); // Type: Result.Result ``` Notice that `'NotFound'` has disappeared from the error type, because it can no longer occur. Error type after each step: - `findUser('u123')`: `'NotFound' | 'Timeout'` - `Result.orElse((error) => { ... })`: `'Timeout'` ### Example: Fallback Sources `orElse` is also useful for trying an alternative when the first attempt fails: ```ts import { Result } from '@praha/byethrow'; type Config = { apiUrl: string; timeout: number }; declare const loadConfigFromFile: () => Result.ResultAsync; declare const loadConfigFromEnv: () => Result.ResultAsync; const config = await Result.pipe( loadConfigFromFile(), Result.orElse(() => loadConfigFromEnv()), ); // Type: Result.Result // Tries the file first, then falls back to environment variables ``` ## Combining `andThen` and `orElse` Both functions can be combined to express flows with both chaining and recovery: ```ts import { Result } from '@praha/byethrow'; type User = { id: string; name: string }; declare const fetchUserFromCache: (id: string) => Result.ResultAsync; declare const fetchUserFromDb: (id: string) => Result.ResultAsync; declare const validateUser: (user: User) => Result.Result; const getValidatedUser = (id: string) => Result.pipe( fetchUserFromCache(id), Result.orElse(() => fetchUserFromDb(id)), Result.andThen(validateUser), ); // Tries the cache first, falls back to the database, then validates the user ``` - `fetchUserFromCache(id)`: creates `Failure` or `Success` - `Result.orElse(() => fetchUserFromDb(id))`: runs on `Failure` and returns `Success` or `Failure` - `Result.andThen(validateUser)`: runs on `Success` and returns `Success` or `Failure` ## References | API | Purpose | | -------------------------------------------------------- | -------------------------------------------- | | [andThen(fn)](/byethrow/api/functions/Result.andThen.md) | Chain the next step using the success value | | [orElse(fn)](/byethrow/api/functions/Result.orElse.md) | Recover from a failure using the error value | --- url: /byethrow/guide/tutorial/chaining/validation-recovery.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Validation and Cleanup Sometimes you want to run an additional step that can fail, without replacing the value you already have. `andThrough` and `orThrough` run such a step and, if it succeeds, keep the original `Result`. ## Running Checks with `andThrough` - `Success(a)`: `fn(a)` returns `Success(b)` → `Success(a)` - `Success(a)`: `fn(a)` returns `Failure(f)` → `Failure(f)` - `Failure(e)`: `fn` is not called → `Failure(e)` `andThrough` calls the given function with the success value, just like `andThen`. The difference is what happens when the function succeeds: - If the function returns a `Success`, its value is discarded and the **original** `Success` is returned. - If the function returns a `Failure`, that `Failure` is returned. - If the input is a `Failure`, the function is not called. ```ts import { Result } from '@praha/byethrow'; const checkPositive = (value: number) => { return 0 < value ? Result.succeed() : Result.fail('Must be positive'); }; const passed = Result.pipe( Result.succeed(5), Result.andThrough(checkPositive), ); // { type: 'Success', value: 5 } - the original value is kept const rejected = Result.pipe( Result.succeed(-10), Result.andThrough(checkPositive), ); // { type: 'Failure', error: 'Must be positive' } const skipped = Result.pipe( Result.fail('error'), Result.andThrough(checkPositive), // Not called ); // { type: 'Failure', error: 'error' } ``` This makes `andThrough` a good fit for validations and for side effects that can fail, such as writing an audit log, where the next step still needs the original value. ### Example: Multiple Validations Each validation only needs to report whether the value is acceptable, so it can simply return `Result.Result`: ```ts import { Result } from '@praha/byethrow'; type User = { name: string; age: number; email: string }; declare const validateName: (user: User) => Result.Result; declare const validateAge: (user: User) => Result.Result; declare const validateEmail: (user: User) => Result.Result; const validateUser = (user: User) => Result.pipe( Result.succeed(user), Result.andThrough(validateName), Result.andThrough(validateAge), Result.andThrough(validateEmail), ); // Type: Result.Result // Returns the original user if every validation passes, otherwise the first error ``` :::tip `andThrough` stops at the first failed validation. To report every validation error at once, use [`collect`](/byethrow/guide/tutorial/combining/aggregating-results.md) instead. ::: ## Cleaning Up with `orThrough` - `Failure(e)`: `fn(e)` returns `Success(b)` → `Failure(e)` - `Failure(e)`: `fn(e)` returns `Failure(f)` → `Failure(f)` - `Success(a)`: `fn` is not called → `Success(a)` `orThrough` is the counterpart of `andThrough` for failures. It calls the given function with the error value, typically to clean up after a failed operation: - If the function returns a `Success`, the **original** `Failure` is returned. - If the function returns a `Failure`, that new `Failure` is returned. - If the input is a `Success`, the function is not called. ```ts import { Result } from '@praha/byethrow'; const cleanedUp = Result.pipe( Result.fail('original error'), Result.orThrough(() => Result.succeed()), ); // { type: 'Failure', error: 'original error' } - the original error is kept const cleanupFailed = Result.pipe( Result.fail('original error'), Result.orThrough(() => Result.fail('cleanup error')), ); // { type: 'Failure', error: 'cleanup error' } const skipped = Result.pipe( Result.succeed(5), Result.orThrough(() => Result.succeed()), // Not called ); // { type: 'Success', value: 5 } ``` Unlike `orElse`, `orThrough` never turns a failure into a success. It is meant for work that has to happen _because_ of a failure, while the failure itself is still reported. ### Example: Rolling Back on Failure Suppose a post is created in two steps: uploading its content, then saving a database record. If saving the record fails, the uploaded file should be deleted, but the caller should still receive the `SavePostFailed` error: ```ts import { Result } from '@praha/byethrow'; declare const uploadFile: (path: string, content: string) => Result.ResultAsync; declare const savePost: (id: string, path: string) => Result.ResultAsync; declare const deleteFile: (path: string) => Result.ResultAsync; const createPost = (id: string, content: string) => { const path = `/posts/${id}`; return Result.pipe( uploadFile(path, content), Result.andThen(() => Result.pipe( savePost(id, path), // Runs only when savePost fails Result.orThrough(() => deleteFile(path)), )), ); }; // Type: Result.ResultAsync ``` `orThrough` is placed right after `savePost`, so the cleanup runs only when saving fails, not when the upload itself fails. ## References | API | Purpose | | -------------------------------------------------------------- | ------------------------------------------------------ | | [andThrough(fn)](/byethrow/api/functions/Result.andThrough.md) | Run a step on success while keeping the original value | | [orThrough(fn)](/byethrow/api/functions/Result.orThrough.md) | Run a step on failure while keeping the original error | --- url: /byethrow/guide/tutorial/chaining/debugging.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Debugging When a pipeline doesn't behave as expected, you want to see the value at each step. `inspect` and `inspectError` let you run a side effect, such as logging, without affecting the `Result` that flows through the pipeline. ## Inspecting Success Values with `inspect` - `Success(a)`: `fn(a)` is called and its return value is ignored → `Success(a)` - `Failure(e)`: `fn` is not called → `Failure(e)` `inspect` calls the given function with the success value and then returns the original `Result` unchanged. If the `Result` is a `Failure`, the function is not called: ```ts import { Result } from '@praha/byethrow'; const success = Result.pipe( Result.succeed(42), Result.inspect((value) => console.log('Value:', value)), Result.map((value) => value * 2), ); // Console: "Value: 42" // { type: 'Success', value: 84 } const failure = Result.pipe( Result.fail('error'), Result.inspect((value) => console.log('Value:', value)), // Not called ); // { type: 'Failure', error: 'error' } ``` ## Inspecting Errors with `inspectError` - `Failure(e)`: `fn(e)` is called and its return value is ignored → `Failure(e)` - `Success(a)`: `fn` is not called → `Success(a)` `inspectError` is the counterpart of `inspect` for errors. It calls the given function with the error value, and does nothing for a `Success`: ```ts import { Result } from '@praha/byethrow'; const failure = Result.pipe( Result.fail('Something went wrong'), Result.inspectError((error) => console.error('Error:', error)), ); // Console: "Error: Something went wrong" // { type: 'Failure', error: 'Something went wrong' } const success = Result.pipe( Result.succeed(42), Result.inspectError((error) => console.error('Error:', error)), // Not called ); // { type: 'Success', value: 42 } ``` ## Example: Tracing a Pipeline Insert `inspect` between the steps you want to observe, and `inspectError` at the end to log whichever step failed: ```ts type Input = { data: string }; type Transformed = { transformedData: string }; type Saved = { id: string }; declare const validate: (input: Input) => Result.Result; declare const transform: (input: Input) => Result.Result; declare const save: (input: Transformed) => Result.Result; // ---cut-before--- import { Result } from '@praha/byethrow'; const processData = (input: Input) => { return Result.pipe( Result.succeed(input), Result.inspect((value) => console.log('Input:', value)), Result.andThrough(validate), Result.andThen(transform), Result.inspect((value) => console.log('After transform:', value)), Result.andThen(save), Result.inspect((value) => console.log('After save:', value)), Result.inspectError((error) => console.error('Pipeline failed:', error)), ); }; ``` ## Things to Keep in Mind - **The return value is ignored.** Even if the function returns a `Failure`, the original `Result` is passed on. If a side effect can fail and its failure matters, use [`andThrough`](/byethrow/guide/tutorial/chaining/validation-recovery.md) or [`orThrough`](/byethrow/guide/tutorial/chaining/validation-recovery.md) instead. - **Async functions are awaited.** If the function returns a `Promise`, the pipeline waits for it before continuing, and becomes asynchronous. - **Not only for debugging.** Placing `inspect` and `inspectError` at the end of a pipeline is also a simple way to act on the final outcome, such as printing output or setting an exit code. See the [Examples](/byethrow/examples/parse-package-json.md) for this pattern. ## References | API | Purpose | | ------------------------------------------------------------------ | -------------------------------------- | | [inspect(fn)](/byethrow/api/functions/Result.inspect.md) | Run a side effect on the success value | | [inspectError(fn)](/byethrow/api/functions/Result.inspectError.md) | Run a side effect on the error value | --- url: /byethrow/guide/tutorial/combining/building-objects.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Building Objects Sometimes you need several values, each produced by an operation that can fail, and later steps depend on earlier ones. The `do` / `bind` / `let` pattern collects these values into a single object, one field at a time. ## Starting with `do` `do` creates a `Success` holding an empty object. It is the starting point of the pattern: ```ts import { Result } from '@praha/byethrow'; const start = Result.do(); // { type: 'Success', value: {} } ``` ## Adding Fields with `bind` - `Success({ a })`: `fn({ a })` returns `Success(b)` → `Success({ a, b })` - `Success({ a })`: `fn({ a })` returns `Failure(f)` → `Failure(f)` - `Failure(e)`: `fn` is not called → `Failure(e)` `bind(name, fn)` adds a field to the accumulated object: 1. It calls `fn` with the object accumulated so far. 2. If `fn` returns a `Success`, its value is added to the object under `name`. 3. If `fn` returns a `Failure`, the pipeline stops and that `Failure` is returned. ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.do(), Result.bind('name', () => Result.succeed('Alice')), Result.bind('age', () => Result.succeed(30)), ); // { type: 'Success', value: { name: 'Alice', age: 30 } } ``` ### Using Previous Values The key feature of `bind` is that each step can use the fields added before it: ```ts declare const fetchUser: (userId: string) => Result.ResultAsync<{ id: string; profileId: string }, 'UserNotFound'>; declare const fetchProfile: (profileId: string) => Result.ResultAsync<{ bio: string }, 'ProfileNotFound'>; // ---cut-before--- import { Result } from '@praha/byethrow'; const result = await Result.pipe( Result.do(), Result.bind('user', () => fetchUser('u123')), Result.bind('profile', ({ user }) => fetchProfile(user.profileId)), // Uses `user` ); // Type: Result.Result<{ user: { id: string; profileId: string }; profile: { bio: string } }, 'UserNotFound' | 'ProfileNotFound'> ``` ### Failures Short-Circuit If any `bind` fails, the remaining steps are skipped: ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.do(), Result.bind('a', () => Result.succeed(1)), Result.bind('b', () => Result.fail('Error!')), // Fails here Result.bind('c', () => Result.succeed(3)), // Skipped ); // { type: 'Failure', error: 'Error!' } ``` ## Adding Plain Values with `let` - `Success({ a })`: `fn({ a })` returns `b` → `Success({ a, b })` - `Failure(e)`: `fn` is not called → `Failure(e)` Some fields are computed from the fields added so far and cannot fail. `let(name, fn)` adds the value returned by `fn` directly, so you don't need to wrap it in `succeed`: ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.do(), Result.bind('price', () => Result.succeed(1000)), Result.bind('quantity', () => Result.succeed(3)), Result.let('total', ({ price, quantity }) => price * quantity), ); // { type: 'Success', value: { price: 1000, quantity: 3, total: 3000 } } ``` This is the same as `Result.bind('total', ({ price, quantity }) => Result.succeed(price * quantity))`, but it shows at a glance that the step cannot fail. :::info `let` does not await a `Promise` for you, and it has no way to represent a failure. If the value comes from an async operation or one that can fail, use `bind` with a function that returns a `Result` or `ResultAsync`. ::: ## Example: Fetching Related Data When one piece of data is needed to fetch another, `bind` keeps every intermediate value available until the end: ```ts declare const fetchOrder: (orderId: string) => Result.ResultAsync<{ id: string; userId: string; productIds: string[] }, 'OrderNotFound'>; declare const fetchUser: (userId: string) => Result.ResultAsync<{ id: string; name: string }, 'UserNotFound'>; declare const fetchProducts: (productIds: string[]) => Result.ResultAsync<{ id: string; name: string; price: number }[], 'ProductNotFound'>; // ---cut-before--- import { Result } from '@praha/byethrow'; type OrderDetails = { orderId: string; customerName: string; products: { id: string; name: string; price: number }[]; totalPrice: number; }; const getOrderDetails = (orderId: string): Result.ResultAsync => { return Result.pipe( Result.do(), Result.bind('order', () => fetchOrder(orderId)), Result.bind('user', ({ order }) => fetchUser(order.userId)), Result.bind('products', ({ order }) => fetchProducts(order.productIds)), Result.map(({ order, user, products }) => ({ orderId: order.id, customerName: user.name, products, totalPrice: products.reduce((sum, product) => sum + product.price, 0), })), ); }; ``` :::tip `bind` runs its steps one after another, which is necessary when a step depends on a previous one. If the operations are independent of each other, `sequence` or `collect` on the [next page](/byethrow/guide/tutorial/combining/aggregating-results.md) is a better fit, since `collect` can also run async operations in parallel. ::: ## References | API | Purpose | | -------------------------------------------------------- | ------------------------------------------------------ | | [do()](/byethrow/api/functions/Result.do.md) | Create a success result holding an empty object | | [bind(name, fn)](/byethrow/api/functions/Result.bind.md) | Add a field computed from the accumulated object | | [let(name, fn)](/byethrow/api/functions/Result.let.md) | Add a plain value computed from the accumulated object | --- url: /byethrow/guide/tutorial/combining/aggregating-results.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Aggregating Results When you have several Results, such as the outcomes of multiple validations or requests, you often want to combine them into a single `Result`. `sequence` and `collect` both do this. They accept an array or an object of Results, and differ in how they handle failures. ## Stopping at the First Failure with `sequence` - `[Success(a), Success(b), Success(c)]`: all values are gathered → `Success([a, b, c])` - `[Success(a), Failure(e), Failure(f)]`: the first error is returned → `Failure(e)` `sequence` returns a `Success` containing all values if every `Result` succeeds. Otherwise, it returns the **first** failure it encounters: ```ts import { Result } from '@praha/byethrow'; // All succeed const success = Result.sequence([ Result.succeed(1), Result.succeed(2), Result.succeed(3), ]); // { type: 'Success', value: [1, 2, 3] } // Returns the first failure const failure = Result.sequence([ Result.succeed(1), Result.fail('error1'), Result.fail('error2'), ]); // { type: 'Failure', error: 'error1' } ``` When given an object, the success value is an object with the same keys: ```ts import { Result } from '@praha/byethrow'; const result = Result.sequence({ name: Result.succeed('Alice'), age: Result.succeed(30), }); // { type: 'Success', value: { name: 'Alice', age: 30 } } ``` ## Collecting Every Error with `collect` - `[Success(a), Success(b), Success(c)]`: all values are gathered → `Success([a, b, c])` - `[Success(a), Failure(e), Failure(f)]`: all errors are gathered → `Failure([e, f])` `collect` also returns a `Success` containing all values if every `Result` succeeds. Otherwise, it returns a `Failure` containing an array of **all** errors: ```ts import { Result } from '@praha/byethrow'; // All succeed const success = Result.collect([ Result.succeed(1), Result.succeed(2), Result.succeed(3), ]); // { type: 'Success', value: [1, 2, 3] } // Returns every failure const failure = Result.collect([ Result.succeed(1), Result.fail('error1'), Result.fail('error2'), ]); // { type: 'Failure', error: ['error1', 'error2'] } ``` ### Example: Form Validation `collect` is ideal for validating a form, where the user should see every problem at once rather than one at a time: ```ts import { Result } from '@praha/byethrow'; type SignUpInput = { name: string; email: string; password: string }; declare const validateName: (name: string) => Result.Result; declare const validateEmail: (email: string) => Result.Result; declare const validatePassword: (password: string) => Result.Result; const validateSignUp = (input: SignUpInput) => Result.collect({ name: validateName(input.name), email: validateEmail(input.email), password: validatePassword(input.password), }); validateSignUp({ name: '', email: 'invalid', password: 'correct horse battery staple' }); // { type: 'Failure', error: ['NameRequired', 'InvalidEmail'] } ``` ## Using a Mapper Function Both functions also accept an array of plain values and a mapper function that converts each value into a `Result`: ```ts import { Result } from '@praha/byethrow'; const parseNumber = (input: string) => { const number = Number(input); if (Number.isNaN(number)) { return Result.fail(`Invalid number: ${input}`); } return Result.succeed(number); }; Result.sequence(['1', 'abc', 'xyz'], parseNumber); // { type: 'Failure', error: 'Invalid number: abc' } Result.collect(['1', 'abc', 'xyz'], parseNumber); // { type: 'Failure', error: ['Invalid number: abc', 'Invalid number: xyz'] } ``` With `sequence`, the mapper is called for one element at a time and is **not called for the remaining elements** once a failure occurs. With `collect`, the mapper is called for every element. ## Async Behavior Both functions accept `ResultAsync` values and return a `ResultAsync` if any input is asynchronous. How the async operations run depends on how you pass them. ### Passing Results Directly When you write `fetchUser(id)` inside an array or object literal, the request starts right there, before `sequence` or `collect` is even called. Both functions only decide how to **wait** for operations that are already running: ```ts type User = { id: string; name: string }; type Order = { id: string }; type FetchError = { source: string; message: string }; declare const fetchUser: (id: string) => Result.ResultAsync; declare const fetchOrders: (userId: string) => Result.ResultAsync; declare const userId: string; // ---cut-before--- import { Result } from '@praha/byethrow'; // Both requests start immediately and run concurrently const result = await Result.collect({ user: fetchUser(userId), orders: fetchOrders(userId), }); // Type: Result.Result<{ user: User; orders: Order[] }, FetchError[]> ``` - `collect` waits for all of them and reports every error. - `sequence` waits for them in order and returns as soon as it finds a failure. The other operations are not cancelled; their results are simply ignored. Failing operation: `task2` `sequence`: returns `Failure(e2)` at 3 - `task1`: 0–3 (Success) - `task2`: 0–2 (Failure) - `task3`: 0–4 (Success, result ignored) `collect`: returns `Failure([e2])` at 4 - `task1`: 0–3 (Success) - `task2`: 0–2 (Failure) - `task3`: 0–4 (Success) ### Using a Mapper Function With a mapper function, the operations are started by `sequence` or `collect` itself, so the difference becomes significant: ```ts type User = { id: string; name: string }; type FetchError = { source: string; message: string }; declare const fetchUser: (id: string) => Result.ResultAsync; declare const runMigration: (name: string) => Result.ResultAsync; // ---cut-before--- import { Result } from '@praha/byethrow'; // collect: all requests start at once and run in parallel const users = await Result.collect(['u1', 'u2', 'u3'], fetchUser); // sequence: each migration starts only after the previous one succeeded, // and the remaining migrations are skipped after a failure const migrations = await Result.sequence( ['001-create-users', '002-add-email', '003-create-posts'], runMigration, ); ``` Failing operation: `fn(2)` `sequence`: returns `Failure(e2)` at 5 - `fn(1)`: 0–3 (Success) - `fn(2)`: 3–5 (Failure) - `fn(3)`: not started `collect`: returns `Failure([e2])` at 4 - `fn(1)`: 0–3 (Success) - `fn(2)`: 0–2 (Failure) - `fn(3)`: 0–4 (Success) :::tip If later operations must not start after a failure, don't create them up front. Use `sequence` with a mapper function, or chain the steps with [`andThen`](/byethrow/guide/tutorial/chaining/chaining-results.md) or [`bind`](/byethrow/guide/tutorial/combining/building-objects.md). ::: ## Choosing Between `sequence` and `collect` | Scenario | Recommended | | ----------------------------------------------------------- | ------------------------ | | Report every error at once, such as for form validation | `collect` | | Run independent async operations in parallel | `collect` | | Only the first error matters | `sequence` | | Run operations one by one and skip the rest after a failure | `sequence` with a mapper | ## References | API | Purpose | | -------------------------------------------------------------- | ---------------------------------------------- | | [sequence(values)](/byethrow/api/functions/Result.sequence.md) | Combine Results, stopping at the first failure | | [collect(values)](/byethrow/api/functions/Result.collect.md) | Combine Results, gathering every error | --- url: /byethrow/guide/tutorial/resolving/unwrapping.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Unwrapping Results At some point, you need to take the value out of a `Result` and hand it to code that doesn't know about Results, such as a web framework or a CLI runner. `unwrap` and `unwrapError` extract the contents of a `Result` as a plain value. ## Extracting the Value with `unwrap` - `Success(a)`: `a` is returned → `a` - `Failure(e)`: `e` is thrown if no default value is given → `throw e` - `Failure(e)`: the default value `d` is returned → `d` `unwrap` returns the success value of a `Result`: ```ts import { Result } from '@praha/byethrow'; const value = Result.unwrap(Result.succeed(42)); // value: 42 ``` If the `Result` is a `Failure`, `unwrap` **throws its error**: ```ts import { Result } from '@praha/byethrow'; const value = Result.unwrap(Result.fail(new Error('Something went wrong'))); // Throws: Error('Something went wrong') ``` ### Providing a Default Value Pass a default value as the second argument to return it instead of throwing: ```ts import { Result } from '@praha/byethrow'; const fallback = Result.unwrap(Result.fail('error'), 0); // fallback: 0 const value = Result.unwrap(Result.succeed(42), 0); // value: 42 (the default is ignored) ``` ## Extracting the Error with `unwrapError` - `Failure(e)`: `e` is returned → `e` - `Success(a)`: `a` is thrown if no default value is given → `throw a` - `Success(a)`: the default value `d` is returned → `d` `unwrapError` is the counterpart of `unwrap`. It returns the error value of a `Result`: ```ts import { Result } from '@praha/byethrow'; const error = Result.unwrapError(Result.fail('Something went wrong')); // error: 'Something went wrong' ``` If the `Result` is a `Success`, `unwrapError` throws its value, unless a default value is provided: ```ts import { Result } from '@praha/byethrow'; const error = Result.unwrapError(Result.succeed(42)); // Throws: 42 const fallback = Result.unwrapError(Result.succeed(42), 'No error'); // fallback: 'No error' ``` ## Unwrapping in a Pipeline When called without a `Result`, both functions return a function that unwraps its argument. This lets you use them as the last step of a pipeline: ```ts import { Result } from '@praha/byethrow'; const value = Result.pipe( Result.succeed(21), Result.map((x) => x * 2), Result.unwrap(), // or Result.unwrap(defaultValue) ); // value: 42 ``` ## Async Results Both functions accept a `ResultAsync` and return a `Promise` of the plain value: ```ts import { Result } from '@praha/byethrow'; const value = await Result.unwrap(Promise.resolve(Result.succeed(42))); // value: 42 const fallback = await Result.unwrap(Promise.resolve(Result.fail('error')), 0); // fallback: 0 ``` ## Where to Unwrap ### At the Boundaries of Your Application Unwrap at the boundaries of your application, such as HTTP handlers and CLI entry points, where plain values have to be handed to the outside world. Handle the errors you expect first, and let `unwrap` throw only what remains: ```ts declare const processRequest: (req: Request) => Result.ResultAsync; // ---cut-before--- import { Result } from '@praha/byethrow'; const handleRequest = async (req: Request): Promise => { return await Result.pipe( processRequest(req), Result.map((result) => { return new Response(JSON.stringify(result), { status: 200 }); }), Result.orElse((error) => { switch (error) { case 'NotFound': return Result.succeed(new Response('Not Found', { status: 404 })); default: return Result.fail(error); } }), // Remaining errors are thrown here, where infrastructure-level // error monitoring such as Sentry or CloudWatch can detect them. Result.unwrap(), ); }; ``` To make sure at compile time that `unwrap` never throws, combine it with [`assertSuccess`](/byethrow/guide/tutorial/resolving/asserting.md) on the next page. ### Not in the Middle of Your Logic Avoid unwrapping in the middle of your logic. Doing so leaves the `Result` world too early and turns expected failures back into exceptions. Keep values wrapped and transform them with functions such as `map`, `andThen`, and `orElse` instead: ```ts import { Result } from '@praha/byethrow'; // ❌ Don't do this const bad = Result.unwrap(Result.succeed(42)) * 2; // ✅ Do this instead const good = Result.pipe( Result.succeed(42), Result.map((x) => x * 2), ); ``` ## References | API | Purpose | | -------------------------------------------------------------------- | ----------------------------------------------------------------- | | [unwrap(result)](/byethrow/api/functions/Result.unwrap.md) | Extract the success value, or throw / return a default on failure | | [unwrapError(result)](/byethrow/api/functions/Result.unwrapError.md) | Extract the error value, or throw / return a default on success | --- url: /byethrow/guide/tutorial/resolving/asserting.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Asserting Results After you have handled every possible error, for example with `orElse`, the error type of a `Result` becomes `never`. `assertSuccess` and `assertFailure` let you state this in your code, and TypeScript verifies it at compile time. ## Asserting Success with `assertSuccess` `assertSuccess` takes a `Result` whose error type is `never` and returns it as a `Success`: ```ts import { Result } from '@praha/byethrow'; const result: Result.Result = Result.succeed(42); const success = Result.assertSuccess(result); // success: { type: 'Success', value: 42 } ``` ### When Errors Remain If the error type is not `never`, meaning some errors might still occur, TypeScript reports a compile error: ```ts // @errors: 2345 import { Result } from '@praha/byethrow'; const result: Result.Result = Result.succeed(42); // ❌ The error type is string, not never const success = Result.assertSuccess(result); ``` ### Handling Every Error with `orElse` Use `orElse` to handle the errors so that the error type becomes `never`: ```ts import { Result } from '@praha/byethrow'; declare const getResult: () => Result.Result; const result = Result.pipe( getResult(), Result.orElse(() => Result.succeed(0)), // The error type is now never Result.assertSuccess, ); // result: { type: 'Success', value: number } ``` If you later add a new error to `getResult` and forget to handle it, `assertSuccess` fails to compile, pointing you to the place that needs updating. ## Asserting Failure with `assertFailure` `assertFailure` is the counterpart of `assertSuccess`. It takes a `Result` whose success type is `never` and returns it as a `Failure`: ```ts import { Result } from '@praha/byethrow'; const result: Result.Result = Result.fail('error'); const failure = Result.assertFailure(result); // failure: { type: 'Failure', error: 'error' } ``` If the success type is not `never`, TypeScript reports a compile error: ```ts // @errors: 2345 import { Result } from '@praha/byethrow'; const result: Result.Result = Result.fail('error'); // ❌ The success type is number, not never const failure = Result.assertFailure(result); ``` ## Unwrapping Safely with `assertSuccess` and `unwrap` `unwrap` throws when it receives a `Failure`. By calling `assertSuccess` first, you guarantee at compile time that there is no `Failure` left, so `unwrap` cannot throw: ```ts import { Result } from '@praha/byethrow'; declare const getResult: () => Result.Result; const value = Result.pipe( getResult(), Result.orElse(() => Result.succeed(0)), // Handle every error Result.assertSuccess, // Verify that no error remains Result.unwrap(), // Cannot throw ); // value: number ``` This pattern is especially useful at the boundaries of your application, where you want to extract the final value safely. ## Compared to Type Guards `assertSuccess` / `assertFailure` and `isSuccess` / `isFailure` serve different purposes: | Function | When the check happens | Purpose | | --------------------------------- | ---------------------- | ---------------------------------------------------- | | `isSuccess` / `isFailure` | Runtime | Branch on whether a `Result` is a success or failure | | `assertSuccess` / `assertFailure` | Compile time | Declare that only one variant is possible | As a safeguard, `assertSuccess` and `assertFailure` also throw an error at runtime if they receive the unexpected variant, for example because of an incorrect type assertion elsewhere. ## References | API | Purpose | | ------------------------------------------------------------------------ | -------------------------------------------------------------------- | | [assertSuccess(result)](/byethrow/api/functions/Result.assertSuccess.md) | Assert that a Result is a Success (the error type must be `never`) | | [assertFailure(result)](/byethrow/api/functions/Result.assertFailure.md) | Assert that a Result is a Failure (the success type must be `never`) | --- url: /byethrow/guide/best-practices/result-vs-throw.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Result vs throw You may have heard the argument: "JavaScript can throw anywhere, and it's impossible to manage every error with `Result`, so there's no point in using `Result` at all." We disagree. The key is that **a `Result` only needs to represent anticipated errors**. There is no need to wrap every possible error in a `Result`. ## Anticipated vs Unexpected Errors Whether an error belongs in a `Result` or should be thrown depends on its nature. ### Anticipated Errors: Use `Result` Anticipated errors are part of your application's business logic. They are expected to happen during normal operation, and the caller can respond to them meaningfully, for example by showing a message to the user or returning a `404` response: - The requested post does not exist - The user doesn't have permission to perform the action - The submitted form contains invalid values Represent these errors in the return type so that callers are forced to handle them: ```ts // @noErrors class PostNotFoundError extends Error {} class PostPermissionError extends Error {} class PostAlreadyDeletedError extends Error {} import { Result } from '@praha/byethrow'; // ---cut-before--- type PostDeleteError = ( | PostNotFoundError | PostPermissionError | PostAlreadyDeletedError ); const deletePost = async (postId: string): Result.ResultAsync => { // Returns a Failure for each business rule violation } ``` ### Unexpected Errors: Let Them Throw Unexpected errors come from the infrastructure or from bugs. The caller usually can't do anything about them other than report them: - Database connection failures - Network timeouts - Out-of-memory errors - Programming errors, such as reading a property of `undefined` Let these errors be thrown, and handle them in one place at the top level, such as a framework's error handler or an error monitoring service like Sentry: ```ts // @noErrors interface Database {} // ---cut-before--- // May throw on connection failures, timeouts, and so on const connectToDatabase = async (): Promise => { // ... }; ``` :::tip When in doubt, ask yourself: **"Will the caller handle this error differently from any other error?"** If the answer is yes, it is an anticipated error and belongs in a `Result`. ::: ## Converting Between the Two In practice, the two kinds of errors meet at the boundaries of your code: - **From throw to `Result`**: When a library signals an anticipated failure by throwing, such as `JSON.parse` on user input, wrap it with [`Result.fn` or `Result.try`](/byethrow/guide/tutorial/basics/wrapping-functions.md). - **From `Result` to throw**: At the entry point of your application, handle the errors you expect and let [`Result.unwrap`](/byethrow/guide/tutorial/resolving/unwrapping.md) throw the rest, so that your error monitoring can pick them up. ## Wrapping Unexpected Errors for Better Stack Traces Sometimes the stack trace of an unexpected error isn't helpful, because it points deep into a library's internals. In that case, you can wrap the operation with `Result.fn` and convert any thrown error into a single `UnexpectedError` class. First, define the error class: :::tip For more details about `@praha/error-factory`, see [Custom Error](/byethrow/guide/best-practices/custom-error.md). ::: ```ts import { ErrorFactory } from '@praha/error-factory'; class UnexpectedError extends ErrorFactory({ name: 'UnexpectedError', message: 'An unexpected error occurred', }) {} ``` Then wrap the operation, keeping the original error as `cause`: ```ts import { ErrorFactory } from '@praha/error-factory'; class UnexpectedError extends ErrorFactory({ name: 'UnexpectedError', message: 'An unexpected error occurred', }) {} const performDatabaseOperation = async (id: string): Promise => Promise.resolve('data'); // ---cut-before--- import { Result } from '@praha/byethrow'; const findRecord = Result.fn({ try: (id: string) => { // May throw query errors, network errors, and so on return performDatabaseOperation(id); }, catch: (error) => new UnexpectedError({ cause: error }), }); const result = await findRecord('123'); if (Result.isFailure(result)) { // The stack trace starts in your code, where the error was wrapped console.error(result.error.stack); // The original error is still available console.error(result.error.cause); } ``` This approach has the following benefits: 1. **Readable stack traces**: The new error is created in your own code, so its stack trace shows where the failure entered your application. 2. **Context**: You can attach information that helps with debugging, such as the arguments of the operation. 3. **Nothing is lost**: The original error remains accessible through the `cause` property. At the entry point of your application, you can still `unwrap` these errors to rethrow them to your error monitoring. ## Conclusion The goal is not to replace every `throw` with a `Result`, but to use each where it fits best. `Result` excels at anticipated, business-level errors that require explicit handling, while `throw` remains the right tool for unexpected errors that should be handled at the infrastructure level. This combination gives you explicit error handling where it matters most, without the burden of wrapping every possible error in your application. --- url: /byethrow/guide/best-practices/importing-result.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Importing Result `@praha/byethrow` exports the same set of functions under two names: `Result` and `R`. Both fully support tree-shaking, so the choice is purely a matter of style. ## Two Import Styles ### `Result`: Explicit The `Result` namespace makes it obvious where each function comes from: ```ts import { Result } from '@praha/byethrow'; const validateUser = (id: string) => { if (!id.startsWith('u')) { return Result.fail(new Error('Invalid ID format')); } return Result.succeed(id); }; const result = Result.pipe( Result.succeed('u123'), Result.andThen(validateUser), Result.map((id) => ({ id, name: 'John Doe' })), ); if (Result.isSuccess(result)) { console.log(result.value); } ``` ### `R`: Concise The `R` alias keeps pipelines short: ```ts import { R } from '@praha/byethrow'; const validateUser = (id: string) => { if (!id.startsWith('u')) { return R.fail(new Error('Invalid ID format')); } return R.succeed(id); }; const result = R.pipe( R.succeed('u123'), R.andThen(validateUser), R.map((id) => ({ id, name: 'John Doe' })), ); if (R.isSuccess(result)) { console.log(result.value); } ``` The examples in this documentation use `Result`, but everything works the same with `R`. ## Tree-Shaking Although you import a namespace, each function is an independent export. Modern bundlers include only the functions you actually use: ```ts import { R } from '@praha/byethrow'; // Only `fn` and the code it depends on end up in the bundle. // Functions such as `andThen` and `pipe` are removed. const parseNumber = R.fn({ try: (input: string) => parseInt(input, 10), catch: () => new Error('Invalid number'), }); ``` ## Choosing a Style - **`Result`** if you prefer explicit, self-descriptive code. It is also easier for newcomers to search for. - **`R`** if you prefer fewer keystrokes and compact pipelines. ### Don't Mix the Two **We strongly recommend choosing one style and using it throughout your codebase.** Mixing them makes code inconsistent and harder to search: ```ts // @filename: mixed-imports.ts // ❌ Mixing both styles import { Result, R } from '@praha/byethrow'; const validateId = (id: string) => { return Result.succeed(id); }; const processData = R.pipe( R.succeed('data'), R.andThen(validateId), ); // @filename: consistent-imports.ts // ✅ Using one style consistently import { Result } from '@praha/byethrow'; const validateId = (id: string) => { return Result.succeed(id); }; const processData = Result.pipe( Result.succeed('data'), Result.andThen(validateId), ); ``` The [consistent-namespace](/byethrow/guide/ecosystem/linter/consistent-namespace.md) lint rule enforces your chosen style and fixes violations automatically. --- url: /byethrow/guide/best-practices/custom-error.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Custom Error Any value can be used as the error of a `Result`, but plain strings and generic `Error` objects make it hard for callers to tell failures apart. We strongly recommend giving each kind of failure its own error type. This page explains the options and how to create custom errors efficiently. ## Two Ways to Define Custom Errors ### 1. Error Classes (Recommended) Define a class that extends the built-in `Error` class, and give it a unique `name`: ```ts import { Result } from '@praha/byethrow'; import { z } from 'zod'; class ValidationError extends Error { override readonly name = 'ValidationError'; } const validateEmail = (email: string): Result.Result => { return Result.pipe( email, Result.parse(z.email()), Result.mapError((issues) => new ValidationError('Invalid email format', { cause: issues })), ); }; ``` ### 2. Tagged Objects Alternatively, use plain objects with a property that identifies the kind of error: ```ts import { Result } from '@praha/byethrow'; import { z } from 'zod'; type ValidationError = { type: 'ValidationError'; message: string; value: string; }; const validateEmail = (email: string): Result.Result => { return Result.pipe( email, Result.parse(z.email()), Result.mapError(() => ({ type: 'ValidationError', message: 'Invalid email format', value: email, })), ); }; ``` ## Why We Recommend Error Classes Both approaches let callers distinguish errors, but error classes have several practical advantages. ### Stack Traces and Error Chaining An `Error` records a stack trace showing where it was created, and the `cause` option keeps the original error that led to it. Together, they make debugging much easier: ```ts type User = { id: string; name: string }; declare const database: { findUser: (id: string) => Promise }; // ---cut-before--- import { Result } from '@praha/byethrow'; class DatabaseError extends Error { override readonly name = 'DatabaseError'; } const fetchUser = (id: string) => Result.try({ try: () => database.findUser(id), // The stack trace points here, and the original error is kept as `cause` catch: (error) => new DatabaseError('Failed to fetch user', { cause: error }), }); ``` ### Compatibility with `throw` Errors in a `Result` sometimes end up being thrown, for example by [`unwrap`](/byethrow/guide/tutorial/resolving/unwrapping.md) at the boundary of your application. Error monitoring tools and runtimes expect thrown values to be `Error` instances. A thrown plain object has no stack trace and is often reported poorly. ## Recommended: Using `@praha/error-factory` Writing error classes by hand quickly becomes repetitive. [`@praha/error-factory`](https://github.com/praha-inc/error-factory) reduces the boilerplate and keeps your errors consistent. ### Installation ```sh [npm] npm install @praha/error-factory ``` ```sh [yarn] yarn add @praha/error-factory ``` ```sh [pnpm] pnpm add @praha/error-factory ``` ```sh [bun] bun add @praha/error-factory ``` ```sh [deno] deno add npm:@praha/error-factory ``` ### Defining Errors Extend the class returned by `ErrorFactory`. The `name` becomes a literal type, which lets TypeScript narrow unions of errors by their `name`: ```ts import { ErrorFactory } from '@praha/error-factory'; class ValidationError extends ErrorFactory({ name: 'ValidationError', message: 'Invalid input provided', }) {} class QueryError extends ErrorFactory({ name: 'QueryError', message: 'An error occurred while executing a query', // Additional fields carried by the error fields: ErrorFactory.fields<{ query: string }>(), }) {} class NotFoundError extends ErrorFactory({ name: 'NotFoundError', message: 'Resource not found', }) {} ``` `message` can also be a function that builds the message from the fields: ```ts import { ErrorFactory } from '@praha/error-factory'; class HttpError extends ErrorFactory({ name: 'HttpError', message: ({ status }) => `Request failed with status ${status}`, fields: ErrorFactory.fields<{ status: number }>(), }) {} ``` ### Using Errors in Results Create the errors wherever a failure occurs, passing the original error as `cause` and filling in any fields: ```ts import { ErrorFactory } from '@praha/error-factory'; class ValidationError extends ErrorFactory({ name: 'ValidationError', message: 'Invalid input provided', }) {} class QueryError extends ErrorFactory({ name: 'QueryError', message: 'An error occurred while executing a query', fields: ErrorFactory.fields<{ query: string }>(), }) {} class NotFoundError extends ErrorFactory({ name: 'NotFoundError', message: 'Resource not found', }) {} type UserRow = { id: string; name: string }; declare const database: { query: (sql: string, params: unknown[]) => Promise }; // ---cut-before--- import { Result } from '@praha/byethrow'; import { z } from 'zod'; const validateId = (id: string) => { return Result.pipe( id, Result.parse(z.string().startsWith('u')), Result.mapError((issues) => new ValidationError({ cause: issues })), ); }; const executeQuery = (sql: string, params: unknown[]) => { return Result.try({ try: () => database.query(sql, params), catch: (error) => new QueryError({ query: sql, cause: error }), }); }; const findUser = (id: string) => { return Result.pipe( validateId(id), Result.andThen((id) => executeQuery('SELECT * FROM users WHERE id = ?', [id])), Result.andThen((row) => { if (!row) { return Result.fail(new NotFoundError()); } return Result.succeed({ id: row.id, name: row.name }); }), ); }; // Type: (id: string) => Result.ResultAsync<{ id: string; name: string }, ValidationError | QueryError | NotFoundError> ``` ### Handling Errors Because each error has a literal `name`, a `switch` statement narrows the error to its exact class, including its fields: ```ts import { Result } from '@praha/byethrow'; import { ErrorFactory } from '@praha/error-factory'; class ValidationError extends ErrorFactory({ name: 'ValidationError', message: 'Invalid input provided', }) {} class QueryError extends ErrorFactory({ name: 'QueryError', message: 'An error occurred while executing a query', fields: ErrorFactory.fields<{ query: string }>(), }) {} class NotFoundError extends ErrorFactory({ name: 'NotFoundError', message: 'Resource not found', }) {} declare const findUser: (id: string) => Result.ResultAsync<{ id: string; name: string }, ValidationError | QueryError | NotFoundError>; // ---cut-before--- const result = await findUser('u123'); if (Result.isSuccess(result)) { console.log(result.value); } else { switch (result.error.name) { case 'ValidationError': console.error('Validation error:', result.error.message); break; case 'QueryError': // Narrowed to QueryError, so `query` is available console.error('Query error:', result.error.message, 'Query:', result.error.query); break; case 'NotFoundError': console.error('Not found error:', result.error.message); break; } } ``` For more ways to handle unions of errors, including exhaustiveness checks, see [Pattern Matching](/byethrow/guide/best-practices/pattern-matching.md). --- url: /byethrow/guide/best-practices/pattern-matching.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Pattern Matching A `Result` often has a union of error types, one for each way the operation can fail. This page shows how to handle each error type appropriately, and how to make sure that none is forgotten. ## The Example The examples on this page use a function that deletes a post and can fail in three different ways. Each error is a class with a unique `name`, as recommended in [Custom Error](/byethrow/guide/best-practices/custom-error.md): ```ts // @noErrors import { ErrorFactory } from '@praha/error-factory'; import { Result } from '@praha/byethrow'; class PostNotFoundError extends ErrorFactory({ name: 'PostNotFoundError', message: 'The requested post was not found.', }) {} class PostPermissionError extends ErrorFactory({ name: 'PostPermissionError', message: 'You do not have permission to perform this action.', }) {} class PostAlreadyDeletedError extends ErrorFactory({ name: 'PostAlreadyDeletedError', message: 'This post has already been deleted.', }) {} type PostDeleteError = ( | PostNotFoundError | PostPermissionError | PostAlreadyDeletedError ); const deletePost = async (postId: string): Result.ResultAsync => { // Returns one of the errors above on failure }; ``` ## Recommended: Using `ts-pattern` We recommend [`ts-pattern`](https://github.com/gvergnaud/ts-pattern) for pattern matching. It has excellent TypeScript support, and `.exhaustive()` reports a compile error if any error type is not handled. ### Installation ```sh [npm] npm install ts-pattern ``` ```sh [yarn] yarn add ts-pattern ``` ```sh [pnpm] pnpm add ts-pattern ``` ```sh [bun] bun add ts-pattern ``` ```sh [deno] deno add npm:ts-pattern ``` ### Matching Errors ```ts // @filename: delete-post.ts import { ErrorFactory } from '@praha/error-factory'; import { Result } from '@praha/byethrow'; export class PostNotFoundError extends ErrorFactory({ name: 'PostNotFoundError', message: 'The requested post was not found.', }) {} export class PostPermissionError extends ErrorFactory({ name: 'PostPermissionError', message: 'You do not have permission to perform this action.', }) {} export class PostAlreadyDeletedError extends ErrorFactory({ name: 'PostAlreadyDeletedError', message: 'This post has already been deleted.', }) {} export type PostDeleteError = ( | PostNotFoundError | PostPermissionError | PostAlreadyDeletedError ); export const deletePost = async (postId: string): Result.ResultAsync => { return Result.succeed(); }; // @filename: index.ts import { deletePost } from './delete-post'; // ---cut-before--- import { Result } from '@praha/byethrow'; import { match } from 'ts-pattern'; await Result.pipe( deletePost('123'), Result.inspectError((error) => { match(error) .with({ name: 'PostNotFoundError' }, () => { console.error('The requested post was not found.'); }) .with({ name: 'PostPermissionError' }, () => { console.error('You do not have permission to perform this action.'); }) .with({ name: 'PostAlreadyDeletedError' }, () => { console.error('This post has already been deleted.'); }) .exhaustive(); // Compile error if a case is missing }), ); ``` ## Alternative: Native TypeScript If you prefer not to add a dependency, TypeScript's built-in features work as well. ### Using a `switch` Statement Because each error has a literal `name`, a `switch` statement narrows the error in each `case`. Adding `satisfies never` in the `default` case gives you the same exhaustiveness check as `ts-pattern`: ```ts // @filename: delete-post.ts import { ErrorFactory } from '@praha/error-factory'; import { Result } from '@praha/byethrow'; export class PostNotFoundError extends ErrorFactory({ name: 'PostNotFoundError', message: 'The requested post was not found.', }) {} export class PostPermissionError extends ErrorFactory({ name: 'PostPermissionError', message: 'You do not have permission to perform this action.', }) {} export class PostAlreadyDeletedError extends ErrorFactory({ name: 'PostAlreadyDeletedError', message: 'This post has already been deleted.', }) {} export type PostDeleteError = ( | PostNotFoundError | PostPermissionError | PostAlreadyDeletedError ); export const deletePost = async (postId: string): Result.ResultAsync => { return Result.succeed(); }; // @filename: index.ts import { deletePost } from './delete-post'; // ---cut-before--- import { Result } from '@praha/byethrow'; await Result.pipe( deletePost('123'), Result.inspectError((error) => { switch (error.name) { case 'PostNotFoundError': console.error('The requested post was not found.'); break; case 'PostPermissionError': console.error('You do not have permission to perform this action.'); break; case 'PostAlreadyDeletedError': console.error('This post has already been deleted.'); break; default: // Compile error if a case is missing error satisfies never; } }), ); ``` ### Using `instanceof` `instanceof` checks also narrow the error type. Note that they don't provide an exhaustiveness check, so a newly added error type can go unnoticed: ```ts // @filename: delete-post.ts import { ErrorFactory } from '@praha/error-factory'; import { Result } from '@praha/byethrow'; export class PostNotFoundError extends ErrorFactory({ name: 'PostNotFoundError', message: 'The requested post was not found.', }) {} export class PostPermissionError extends ErrorFactory({ name: 'PostPermissionError', message: 'You do not have permission to perform this action.', }) {} export class PostAlreadyDeletedError extends ErrorFactory({ name: 'PostAlreadyDeletedError', message: 'This post has already been deleted.', }) {} export type PostDeleteError = ( | PostNotFoundError | PostPermissionError | PostAlreadyDeletedError ); export const deletePost = async (postId: string): Result.ResultAsync => { return Result.succeed(); }; // @filename: index.ts import { deletePost, PostNotFoundError, PostPermissionError, PostAlreadyDeletedError } from './delete-post'; // ---cut-before--- import { Result } from '@praha/byethrow'; await Result.pipe( deletePost('123'), Result.inspectError((error) => { if (error instanceof PostNotFoundError) { console.error('The requested post was not found.'); } if (error instanceof PostPermissionError) { console.error('You do not have permission to perform this action.'); } if (error instanceof PostAlreadyDeletedError) { console.error('This post has already been deleted.'); } }), ); ``` ## Where to Match The examples above use `inspectError` to run a side effect for each error. The same techniques work in any function that receives the error: - [`inspectError`](/byethrow/guide/tutorial/chaining/debugging.md): Run a side effect, such as logging or printing a message. - [`mapError`](/byethrow/guide/tutorial/chaining/mapping-results.md): Convert each error into another value, such as an HTTP response. - [`orElse`](/byethrow/guide/tutorial/chaining/chaining-results.md): Recover from some errors and pass the others on. --- url: /byethrow/guide/ecosystem/llm-integration.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # LLM Integration AI assistants often don't know about byethrow, or only know an outdated version of its API. byethrow provides its documentation in forms that assistants can read, so that they can give accurate guidance for your code. ## Agent Skills (Recommended) The `@praha/byethrow-docs` package bundles the complete documentation as Markdown files, together with a CLI that sets up your AI assistant to use them. This is the recommended approach, because: - The documentation is stored in your project, so it works offline without any server. - Its version always matches the version of `@praha/byethrow` you install. - The assistant can search the documentation and read only the parts it needs. ### Installation Install the package as a development dependency, using the same version as `@praha/byethrow`: ```sh [npm] npm install -D @praha/byethrow-docs ``` ```sh [yarn] yarn add -D @praha/byethrow-docs ``` ```sh [pnpm] pnpm add -D @praha/byethrow-docs ``` ```sh [bun] bun add -D @praha/byethrow-docs ``` ```sh [deno] deno add -D npm:@praha/byethrow-docs ``` ### Setup Run the `init` command for your AI assistant. It creates a configuration file that tells the assistant where the documentation is and how to search it: ```bash # Claude Code (creates .claude/skills/byethrow/SKILL.md) npx @praha/byethrow-docs init claude # GitHub Copilot (creates .github/skills/byethrow/SKILL.md) npx @praha/byethrow-docs init copilot # Cursor (creates .cursor/rules/byethrow/RULE.md) npx @praha/byethrow-docs init cursor ``` Commit the generated file so that everyone on your team gets the same setup. From then on, the assistant consults the byethrow documentation whenever it works on related code. ### CLI Commands The assistant uses the following commands to explore the documentation. You can also run them yourself: ```bash # List all available documents npx @praha/byethrow-docs list # List documents matching a keyword npx @praha/byethrow-docs list --query "pipe" # Search the documentation (up to 5 results by default) npx @praha/byethrow-docs search "your query" --limit 10 # Show the table of contents of a document npx @praha/byethrow-docs toc path/to/document.md ``` ## llms.txt This website also publishes its content following the [llms.txt](https://llmstxt.org/) convention. Pass these URLs to an assistant that can read web pages: | URL | Content | | -------------------------------------------------------------------------------------------------------- | ---------------------------------------------- | | [https://praha-inc.github.io/byethrow/llms.txt](https://praha-inc.github.io/byethrow/llms.txt) | An index of all pages with short descriptions | | [https://praha-inc.github.io/byethrow/llms-full.txt](https://praha-inc.github.io/byethrow/llms-full.txt) | The full content of all pages in a single file | Every page is also available as Markdown by adding `.md` to its URL, for example [https://praha-inc.github.io/byethrow/guide/start/quick.md](https://praha-inc.github.io/byethrow/guide/start/quick.md). --- url: /byethrow/guide/ecosystem/testing.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Testing `@praha/byethrow-testing` provides custom matchers for asserting `Result` values, making your tests shorter and their failure messages clearer. ## Installation ```sh [npm] npm install -D @praha/byethrow-testing ``` ```sh [yarn] yarn add -D @praha/byethrow-testing ``` ```sh [pnpm] pnpm add -D @praha/byethrow-testing ``` ```sh [bun] bun add -D @praha/byethrow-testing ``` ```sh [deno] deno add -D npm:@praha/byethrow-testing ``` ## Setup Register the matchers in a setup file, then load that file from your test runner's configuration. ### Vitest ```ts title="vitest.setup.ts" import { resultMatchers } from '@praha/byethrow-testing'; import { expect } from 'vitest'; import type { ResultMatchers } from '@praha/byethrow-testing'; declare module 'vitest' { interface Matchers extends ResultMatchers {} } expect.extend(resultMatchers); ``` ```ts title="vitest.config.ts" import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { setupFiles: ['./vitest.setup.ts'], }, }); ``` ### Jest ```ts title="jest.setup.ts" import { expect } from '@jest/globals'; import { resultMatchers } from '@praha/byethrow-testing'; import type { ResultMatchers } from '@praha/byethrow-testing'; declare module 'expect' { interface Matchers extends ResultMatchers {} } expect.extend(resultMatchers); ``` ```ts title="jest.config.ts" export default { setupFilesAfterEnv: ['./jest.setup.ts'], }; ``` ### Rstest ```ts title="rstest.setup.ts" import { resultMatchers } from '@praha/byethrow-testing'; import { expect } from '@rstest/core'; import type { ResultMatchers } from '@praha/byethrow-testing'; declare module '@rstest/core' { interface Matchers extends ResultMatchers {} } expect.extend(resultMatchers); ``` ```ts title="rstest.config.ts" import { defineConfig } from '@rstest/core'; export default defineConfig({ setupFiles: ['./rstest.setup.ts'], }); ``` ## Matchers ### `toBeSuccess(callback?)` Asserts that the received value is a `Success`. Optionally, pass a callback to make further assertions on the success value: ```ts import type { ResultMatchers } from '@praha/byethrow-testing'; declare module 'vitest' { interface Matchers extends ResultMatchers {} } // ---cut-before--- import { Result } from '@praha/byethrow'; import { test, expect } from 'vitest'; test('result is success', () => { const result = Result.succeed(42); expect(result).toBeSuccess(); }); test('result is success with value', () => { const result = Result.succeed(42); expect(result).toBeSuccess((value) => { expect(value).toBe(42); }); }); ``` The callback is only called when the result is a `Success`, and `value` is typed as the success type of the `Result`. ### `toBeFailure(callback?)` Asserts that the received value is a `Failure`. Optionally, pass a callback to make further assertions on the error value: ```ts import type { ResultMatchers } from '@praha/byethrow-testing'; declare module 'vitest' { interface Matchers extends ResultMatchers {} } // ---cut-before--- import { Result } from '@praha/byethrow'; import { test, expect } from 'vitest'; test('result is failure', () => { const result = Result.fail(new Error('something went wrong')); expect(result).toBeFailure(); }); test('result is failure with error', () => { const result = Result.fail(new Error('something went wrong')); expect(result).toBeFailure((error) => { expect(error.message).toBe('something went wrong'); }); }); ``` ## Tips ### Testing Async Results The matchers check the value they receive synchronously, so `await` a `ResultAsync` before passing it to `expect`: ```ts import type { ResultMatchers } from '@praha/byethrow-testing'; declare module 'vitest' { interface Matchers extends ResultMatchers {} } // ---cut-before--- import { Result } from '@praha/byethrow'; import { test, expect } from 'vitest'; const fetchAnswer = async (): Result.ResultAsync => Result.succeed(42); test('async result is success', async () => { const result = await fetchAnswer(); expect(result).toBeSuccess((value) => { expect(value).toBe(42); }); }); ``` ### Don't Use `.not` `.not.toBeSuccess()` and `.not.toBeFailure()` are not supported and always fail. Use the opposite matcher instead: `toBeFailure()` rather than `.not.toBeSuccess()`, and vice versa. ### Enforce the Matchers with the Linter The [prefer-result-matchers](/byethrow/guide/ecosystem/linter/prefer-result-matchers.md) lint rule detects assertions such as `expect(Result.isSuccess(result)).toBe(true)` and rewrites them to use these matchers. --- url: /byethrow/guide/ecosystem/linter/index.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Linter Plugin `@praha/byethrow-oxlint` is an [Oxlint](https://oxc.rs/docs/guide/usage/linter) plugin that enforces the best practices described in this documentation. It catches common mistakes, such as throwing inside a pipeline or using vague error types, and fixes many of them automatically. ## Installation ```sh [npm] npm install -D @praha/byethrow-oxlint ``` ```sh [yarn] yarn add -D @praha/byethrow-oxlint ``` ```sh [pnpm] pnpm add -D @praha/byethrow-oxlint ``` ```sh [bun] bun add -D @praha/byethrow-oxlint ``` ```sh [deno] deno add -D npm:@praha/byethrow-oxlint ``` ## Setup ### Using the Recommended Preset The easiest way to get started is to extend the recommended preset: ```ts title="oxlint.config.ts" import oxlintByethrowPlugin from '@praha/byethrow-oxlint'; import { defineConfig } from 'oxlint'; export default defineConfig({ extends: [ oxlintByethrowPlugin.recommended, ], }); ``` The preset enables every rule as an error with its default options. [prefer-result-matchers](/byethrow/guide/ecosystem/linter/prefer-result-matchers.md), which is about test code, is only enabled for test files (`**/*.test.*`, `**/*.test-d.*`, and `**/__tests__/**/*`). ### Configuring Rules Manually For fine-grained control, load the plugin and enable individual rules: ```ts title="oxlint.config.ts" import { defineConfig } from 'oxlint'; export default defineConfig({ jsPlugins: [ { name: 'byethrow', specifier: '@praha/byethrow-oxlint', }, ], rules: { 'byethrow/consistent-namespace': 'error', 'byethrow/no-ambiguous-error-type': 'error', // ... }, }); ``` ## Settings By default, the plugin recognizes imports of `Result` and `R` from `@praha/byethrow`. If you re-export `@praha/byethrow` from your own package, add a `byethrow` key under `settings` so that the plugin recognizes it too: | Option | Type | Default | Description | | ----------- | -------------------- | ------------------- | ----------------------------------------------- | | `module` | `string \| string[]` | `"@praha/byethrow"` | Module specifiers to treat as byethrow | | `namespace` | `string \| string[]` | `["Result", "R"]` | Import names to treat as the byethrow namespace | ```ts title="oxlint.config.ts" import { defineConfig } from 'oxlint'; export default defineConfig({ settings: { byethrow: { module: ['@praha/byethrow', '@my-org/result'], namespace: ['Result', 'R'], }, }, }); ``` ## Rules | Rule | Description | Fixable | | ------------------------------------------------------------------------------------------ | ------------------------------------------------------ | ------- | | [consistent-namespace](/byethrow/guide/ecosystem/linter/consistent-namespace.md) | Enforce a consistent namespace alias (`Result` or `R`) | ✅ | | [no-ambiguous-error-type](/byethrow/guide/ecosystem/linter/no-ambiguous-error-type.md) | Disallow non-specific error types | | | [no-ambiguous-success-type](/byethrow/guide/ecosystem/linter/no-ambiguous-success-type.md) | Disallow non-specific success types | | | [no-negated-type-guards](/byethrow/guide/ecosystem/linter/no-negated-type-guards.md) | Disallow negated `isSuccess` / `isFailure` | ✅ | | [no-throw-in-callback](/byethrow/guide/ecosystem/linter/no-throw-in-callback.md) | Disallow `throw` in byethrow callbacks | | | [no-try-catch-in-callback](/byethrow/guide/ecosystem/linter/no-try-catch-in-callback.md) | Disallow `try-catch` in byethrow callbacks | | | [prefer-result-async](/byethrow/guide/ecosystem/linter/prefer-result-async.md) | Prefer `ResultAsync` over `Promise` | ✅ | | [prefer-result-matchers](/byethrow/guide/ecosystem/linter/prefer-result-matchers.md) | Prefer `toBeSuccess` / `toBeFailure` matchers in tests | ✅ | | [prefer-result-maybe-async](/byethrow/guide/ecosystem/linter/prefer-result-maybe-async.md) | Prefer `ResultMaybeAsync` over `Result \| ResultAsync` | ✅ | --- url: /byethrow/guide/ecosystem/linter/consistent-namespace.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # consistent-namespace Enforces that `@praha/byethrow` is always imported under the same namespace alias, either `Result` or `R`. This rule is auto-fixable. The fix renames the import and every reference to it. ## Rule Details `@praha/byethrow` exports the same functions as both `Result` and `R`. Using both in one codebase makes the code inconsistent and harder to search, as explained in [Importing Result](/byethrow/guide/best-practices/importing-result.md). This rule reports every import whose local name is not the preferred alias. ### Incorrect ```ts // ❌ R is used although Result is preferred import { R } from '@praha/byethrow'; const success = R.succeed(42); ``` ```ts // ❌ Mixing Result and R import { Result, R } from '@praha/byethrow'; const success = Result.succeed(42); const failure = R.fail(new Error('Something went wrong')); ``` ### Correct ```ts // ✅ Using Result consistently import { Result } from '@praha/byethrow'; const success = Result.succeed(42); const failure = Result.fail(new Error('Something went wrong')); ``` ## Options The rule accepts the preferred alias as a string. The default is `"Result"`. To prefer `R` instead: ```ts title="oxlint.config.ts" import { defineConfig } from 'oxlint'; export default defineConfig({ rules: { 'byethrow/consistent-namespace': ['error', 'R'], }, }); ``` With this option, the following code is correct: ```ts // ✅ Using R consistently import { R } from '@praha/byethrow'; const success = R.succeed(42); const failure = R.fail(new Error('Something went wrong')); ``` --- url: /byethrow/guide/ecosystem/linter/no-ambiguous-error-type.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # no-ambiguous-error-type Disallows non-specific types in the error position of `Result`, `ResultAsync`, and `ResultMaybeAsync`. ## Rule Details When the error type of a `Result` is vague, callers cannot tell the different failure cases apart and cannot handle them exhaustively. Use a concrete, domain-specific error type instead, as described in [Custom Error](/byethrow/guide/best-practices/custom-error.md). The following types are reported in the error position: - `unknown` and `any` - Primitive types: `string`, `number`, `boolean`, `bigint`, `symbol`, `null`, and `undefined` - `object` and `{}` - The base `Error` class The rule checks explicit type annotations such as `Result.Result`. Types inferred by TypeScript are not checked. ### Incorrect ```ts import { Result } from '@praha/byethrow'; // ❌ unknown type FindUserResult = Result.Result; // ❌ A primitive type type ParseResult = Result.Result; // ❌ The base Error class type SaveResult = Result.ResultAsync; ``` ### Correct ```ts import { Result } from '@praha/byethrow'; class UserNotFoundError extends Error { override readonly name = 'UserNotFoundError'; } // ✅ A concrete error class type FindUserResult = Result.Result; ``` ## Options This rule has no options. --- url: /byethrow/guide/ecosystem/linter/no-ambiguous-success-type.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # no-ambiguous-success-type Disallows non-specific types in the success position of `Result`, `ResultAsync`, and `ResultMaybeAsync`. ## Rule Details When the success type of a `Result` is vague, callers don't know what they receive on success and have to check or cast the value themselves. Use a concrete type instead. The following types are reported in the success position: `unknown`, `any`, `object`, and `{}`. `void` is allowed for operations that don't return a value. The rule checks explicit type annotations such as `Result.Result`. Types inferred by TypeScript are not checked. ### Incorrect ```ts import { Result } from '@praha/byethrow'; class FetchError extends Error {} // ❌ unknown type FetchResult1 = Result.Result; // ❌ any type FetchResult2 = Result.Result; // ❌ object type FetchResult3 = Result.Result; ``` ### Correct ```ts import { Result } from '@praha/byethrow'; class FetchError extends Error {} // ✅ A concrete type type FetchResult = Result.Result<{ id: string }, FetchError>; // ✅ void for operations that return no value type DeleteResult = Result.Result; ``` :::tip When a value really is unknown, such as a parsed JSON body, validate it with [`Result.parse`](/byethrow/guide/tutorial/basics/parsing-values.md) to obtain a concrete type. ::: ## Options This rule has no options. --- url: /byethrow/guide/ecosystem/linter/no-negated-type-guards.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # no-negated-type-guards Disallows using the negation operator (`!`) on `Result.isSuccess()` or `Result.isFailure()`. This rule is auto-fixable. The fix replaces the negated call with the opposite type guard. ## Rule Details `!Result.isSuccess(result)` means the same as `Result.isFailure(result)`, but the negated form takes an extra mental step to read. Since a `Result` is always either a success or a failure, there is always a direct type guard you can use instead. ### Incorrect ```ts import { Result } from '@praha/byethrow'; declare const result: Result.Result; // ❌ Negating isSuccess if (!Result.isSuccess(result)) { // handle failure } // ❌ Negating isFailure if (!Result.isFailure(result)) { // handle success } ``` ### Correct ```ts import { Result } from '@praha/byethrow'; declare const result: Result.Result; // ✅ Using the direct type guard if (Result.isFailure(result)) { // handle failure } if (Result.isSuccess(result)) { // handle success } ``` ## Options This rule has no options. --- url: /byethrow/guide/ecosystem/linter/no-throw-in-callback.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # no-throw-in-callback Disallows `throw` statements inside callbacks passed to `@praha/byethrow` functions, such as `Result.andThen`, `Result.map`, and `Result.fn`. ## Rule Details Throwing inside a callback turns an expected failure back into an exception. The error disappears from the `Result` type, and callers can no longer see or handle it. Return `Result.fail()` instead, so that the error stays explicit and composable. This also applies to the `try` callback of `Result.fn` and `Result.try`. Those callbacks are meant to wrap code that throws on its own, not to signal failures with your own `throw`. ### Incorrect ```ts import { Result } from '@praha/byethrow'; // ❌ Throwing inside a callback const result = Result.pipe( Result.succeed(32), Result.andThen((value) => { if (value < 0) throw new RangeError('negative value'); return Result.succeed(value * 2); }), ); ``` ### Correct ```ts class NegativeValueError extends Error {} // ---cut-before--- import { Result } from '@praha/byethrow'; // ✅ Returning a Failure const result = Result.pipe( Result.succeed(32), Result.andThen((value) => { if (value < 0) return Result.fail(new NegativeValueError()); return Result.succeed(value * 2); }), ); ``` ## Options This rule has no options. --- url: /byethrow/guide/ecosystem/linter/no-try-catch-in-callback.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # no-try-catch-in-callback Disallows `try-catch` blocks inside callbacks passed to `@praha/byethrow` functions, such as `Result.andThen` and `Result.map`. ## Rule Details A `try-catch` inside a callback is a sign that error handling has escaped the `Result` model. Wrap the throwing code with [`Result.fn()` or `Result.try()`](/byethrow/guide/tutorial/basics/wrapping-functions.md) instead, and keep the pipeline itself free of `try-catch`. ### Incorrect ```ts class ParseError extends Error {} // ---cut-before--- import { Result } from '@praha/byethrow'; // ❌ try-catch inside a callback const result = Result.pipe( Result.succeed('{"key": "value"}'), Result.andThen((value) => { try { return Result.succeed(JSON.parse(value)); } catch { return Result.fail(new ParseError()); } }), ); ``` ### Correct ```ts class ParseError extends Error {} // ---cut-before--- import { Result } from '@praha/byethrow'; const parseJson = Result.fn({ try: (value: string) => JSON.parse(value) as unknown, catch: (error) => new ParseError('Invalid JSON', { cause: error }), }); // ✅ Wrapping the throwing code with Result.fn() const result = Result.pipe( Result.succeed('{"key": "value"}'), Result.andThen(parseJson), ); ``` ## Options This rule has no options. --- url: /byethrow/guide/ecosystem/linter/prefer-result-async.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # prefer-result-async Enforces the use of `ResultAsync` instead of `Promise>`. This rule is auto-fixable. ## Rule Details `ResultAsync` is an alias for `Promise>`. The alias is shorter and makes it immediately clear that a function returns an asynchronous `Result`. ### Incorrect ```ts import { Result } from '@praha/byethrow'; class UserNotFoundError extends Error {} type User = { id: string; name: string }; // ❌ Promise> declare const findUser: (id: string) => Promise>; ``` ### Correct ```ts import { Result } from '@praha/byethrow'; class UserNotFoundError extends Error {} type User = { id: string; name: string }; // ✅ ResultAsync declare const findUser: (id: string) => Result.ResultAsync; ``` ## Options This rule has no options. --- url: /byethrow/guide/ecosystem/linter/prefer-result-matchers.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # prefer-result-matchers Enforces the use of the `toBeSuccess()` / `toBeFailure()` matchers from [`@praha/byethrow-testing`](/byethrow/guide/ecosystem/testing.md) in tests. This rule is auto-fixable. In the recommended preset, it is only enabled for test files. ## Rule Details Asserting on the boolean returned by `Result.isSuccess()` is noisy, and a failed assertion only tells you that `false` was not `true`. Calling `Result.unwrap()` in a test throws an unhelpful error when the result is a failure. The dedicated matchers are shorter, print the received `Result` when they fail, and give you a typed value in their callback. This rule reports the following patterns: - `expect(Result.isSuccess(result))` / `expect(Result.isFailure(result))` followed by `.toBe()`, `.toBeTruthy()`, or `.toBeFalsy()` - `assert(Result.isSuccess(result))` / `assert(Result.isFailure(result))` - `Result.unwrap(result)` / `Result.unwrapError(result)` ### Incorrect ```ts import { Result } from '@praha/byethrow'; import { assert, expect } from 'vitest'; declare const result: Result.Result; // ❌ Asserting on the boolean returned by isSuccess / isFailure expect(Result.isSuccess(result)).toBe(true); expect(Result.isFailure(result)).toBeTruthy(); assert(Result.isSuccess(result)); // ❌ Unwrapping the result to assert on its value expect(Result.unwrap(result)).toBe('hello'); ``` ### Correct ```ts import type { ResultMatchers } from '@praha/byethrow-testing'; declare module 'vitest' { interface Matchers extends ResultMatchers {} } // ---cut-before--- import { Result } from '@praha/byethrow'; import { expect } from 'vitest'; declare const result: Result.Result; // ✅ Using the dedicated matchers expect(result).toBeSuccess(); expect(result).toBeFailure(); // ✅ Asserting on the value in the callback expect(result).toBeSuccess((value) => { expect(value).toBe('hello'); }); expect(result).toBeFailure((error) => { expect(error).toBeInstanceOf(Error); }); ``` See [Testing](/byethrow/guide/ecosystem/testing.md) for how to set up `@praha/byethrow-testing`. ## Options This rule has no options. --- url: /byethrow/guide/ecosystem/linter/prefer-result-maybe-async.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # prefer-result-maybe-async Enforces the use of `ResultMaybeAsync` instead of the union `Result | ResultAsync`. This rule is auto-fixable. ## Rule Details `ResultMaybeAsync` is an alias for `Result | ResultAsync`. The alias is shorter and clearly expresses that the value may be either synchronous or asynchronous. ### Incorrect ```ts import { Result } from '@praha/byethrow'; class UserNotFoundError extends Error {} type User = { id: string; name: string }; // ❌ The explicit union type FindUser = (id: string) => Result.Result | Result.ResultAsync; ``` ### Correct ```ts import { Result } from '@praha/byethrow'; class UserNotFoundError extends Error {} type User = { id: string; name: string }; // ✅ ResultMaybeAsync type FindUser = (id: string) => Result.ResultMaybeAsync; ``` ## Options This rule has no options. --- url: /byethrow/examples/parse-package-json.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Parse package.json [Source Code](https://github.com/praha-inc/byethrow/tree/main/examples/parse-package-json) This example reads the `package.json` file in the current directory, validates its contents, and prints the package name and version. Every step that can fail returns a `Result`, and each kind of failure is reported with its own message. ## What This Example Shows - **Wrapping Node.js APIs**: `readFile` wraps `fs.readFile` with [`Result.fn`](/byethrow/guide/tutorial/basics/wrapping-functions.md) and converts file system errors into a `ReadFileError`. - **Parsing and validation**: `parsePackageJson` parses the text with `Result.try` and validates it against a Zod schema with [`Result.parse`](/byethrow/guide/tutorial/basics/parsing-values.md). Any failure is converted into a `ParsePackageJsonError` with `Result.mapError`. - **Composing steps**: The entry point chains both steps with `Result.pipe` and `Result.andThen`. - **Handling the outcome**: `Result.inspect` prints the result, while `Result.inspectError` uses [`ts-pattern`](/byethrow/guide/best-practices/pattern-matching.md) to print a message for each error type and sets the exit code. - **Testing**: The tests assert results with the matchers from [`@praha/byethrow-testing`](/byethrow/guide/ecosystem/testing.md). [Open in StackBlitz](https://stackblitz.com/github/praha-inc/byethrow/tree/main/examples/parse-package-json?file=src%2Findex.ts) --- url: /byethrow/examples/api-request-cli.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # API Request CLI [Source Code](https://github.com/praha-inc/byethrow/tree/main/examples/api-request-cli) This example is a command-line application that fetches data from [PokéAPI](https://pokeapi.co/). `list` prints a page of Pokémon names, and `describe ` prints the details of a single Pokémon. It shows how to build a robust HTTP client where every failure is represented in the type. ## What This Example Shows - **Typed HTTP errors**: The `fetch` wrapper distinguishes network errors, timeouts, non-OK HTTP statuses, and invalid JSON, each as its own error class in a `FetchError` union. - **Timeouts**: A timeout that resolves to a `Failure` races against the request with `Promise.race`. - **Rejecting responses**: `Result.andThen` turns a response with a non-OK status into a `Failure`, as described in [Chaining Results](/byethrow/guide/tutorial/chaining/chaining-results.md). - **Reusable wrappers**: `retry` and `cache` are higher-order functions that wrap any function returning a `ResultAsync`, and are applied with `Result.pipe`. - **Response validation**: API responses are validated with a Valibot schema and [`Result.parse`](/byethrow/guide/tutorial/basics/parsing-values.md). - **Input validation**: The `--page` argument is converted to an integer with a function that returns a `Result`. [Open in StackBlitz](https://stackblitz.com/github/praha-inc/byethrow/tree/main/examples/api-request-cli?file=src%2Findex.ts) --- url: /byethrow/api/index.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # byethrow ## Namespaces | Namespace | Description | | ----------------------------------------- | -------------------------------------------------------------------------- | | [Result](/byethrow/api/modules/Result.md) | Re-exports core Result-handling utilities under two convenient namespaces: | ## References ### R Renames and re-exports [Result](/byethrow/api/modules/Result.md) --- url: /byethrow/api/modules/Result.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Namespace: Result Re-exports core Result-handling utilities under two convenient namespaces: - `Result`: Verbose and explicit usage - `R`: Shorthand alias for more concise code ## Examples **Basic Usage** ```ts import { Result } from '@praha/byethrow'; const validateId = (id: string) => { if (!id.startsWith('u')) { return Result.fail(new Error('Invalid ID format')); } return Result.succeed(); }; const findUser = Result.fn({ try: (id: string) => { return { id, name: 'John Doe' }; }, catch: (error) => new Error('Failed to find user', { cause: error }), }); const result = Result.pipe( Result.succeed('u123'), Result.andThrough(validateId), Result.andThen(findUser), ); if (Result.isSuccess(result)) { console.log(result.value); // User found: John Doe } ``` **Shorthand Usage** ```ts import { R } from '@praha/byethrow'; const validateId = (id: string) => { if (!id.startsWith('u')) { return R.fail(new Error('Invalid ID format')); } return R.succeed(); }; const findUser = R.fn({ try: (id: string) => { return { id, name: 'John Doe' }; }, catch: (error) => new Error('Failed to find user', { cause: error }), }); const result = R.pipe( R.succeed('u123'), R.andThrough(validateId), R.andThen(findUser), ); if (R.isSuccess(result)) { console.log(result.value); // User found: John Doe } ``` ## Core Types | Type Alias | Description | | ------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- | | [Failure](/byethrow/api/types/Result.Failure.md) | Represents a failed result. | | [Result](/byethrow/api/types/Result.Result.md) | A union type representing either a success or a failure. | | [ResultAsync](/byethrow/api/types/Result.ResultAsync.md) | An asynchronous variant of [Result](/byethrow/api/types/Result.Result.md), wrapped in a `Promise`. | | [ResultFor](/byethrow/api/types/Result.ResultFor.md) | Resolves to the appropriate Result type (sync or async) based on the input type. | | [ResultMaybeAsync](/byethrow/api/types/Result.ResultMaybeAsync.md) | A result that may be either synchronous or asynchronous. | | [Success](/byethrow/api/types/Result.Success.md) | Represents a successful result. | ## Infer Types | Type Alias | Description | | ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | [InferFailure](/byethrow/api/types/Result.InferFailure.md) | Infers the [Failure](/byethrow/api/types/Result.Failure.md) value type `E` from a Result or a function returning a Result. | | [InferSuccess](/byethrow/api/types/Result.InferSuccess.md) | Infers the [Success](/byethrow/api/types/Result.Success.md) value type `T` from a Result or a function returning a Result. | ## Creators | Function | Description | | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [do](/byethrow/api/functions/Result.do.md) | Alias for `succeed({})`. Commonly used as a neutral base value in functional chains or monadic pipelines. | | [fail](/byethrow/api/functions/Result.fail.md) | Creates a [Failure](/byethrow/api/types/Result.Failure.md) result from a given error. | | [fn](/byethrow/api/functions/Result.fn.md) | Wraps a function that may throw and returns a new function that returns a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). | | [succeed](/byethrow/api/functions/Result.succeed.md) | Creates a [Success](/byethrow/api/types/Result.Success.md) result from a given value. | | [try](/byethrow/api/functions/Result.try.md) | Executes a function that may throw and wraps the result in a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). | ## Combinators | Function | Description | | -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [andThen](/byethrow/api/functions/Result.andThen.md) | Chains the next computation using the success value of a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). If the original result is a [Failure](/byethrow/api/types/Result.Failure.md), it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is. | | [andThrough](/byethrow/api/functions/Result.andThrough.md) | Runs an additional computation using the success value of a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md), but **returns the original result** if the additional computation is successful. | | [bind](/byethrow/api/functions/Result.bind.md) | Chains another [Result](/byethrow/api/types/Result.Result.md)-producing computation and **merges its success value** into the existing object under the specified key. | | [inspect](/byethrow/api/functions/Result.inspect.md) | Executes a side effect function on the success value of a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md), 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](/byethrow/api/functions/Result.inspectError.md) | Executes a side effect function on the error value of a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md), 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](/byethrow/api/functions/Result.let.md) | Computes a **plain value** from the current success object and attaches it to the existing object under the specified key. | | [map](/byethrow/api/functions/Result.map.md) | Applies a transformation function to the success value of a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). If the input is a [Failure](/byethrow/api/types/Result.Failure.md), it will be returned unchanged. | | [mapError](/byethrow/api/functions/Result.mapError.md) | Applies a transformation function to the error value of a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). If the input is a [Success](/byethrow/api/types/Result.Success.md), it will be returned unchanged. | | [orElse](/byethrow/api/functions/Result.orElse.md) | Chains the next computation using the error value of a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). If the original result is a [Success](/byethrow/api/types/Result.Success.md), it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is. | | [orThrough](/byethrow/api/functions/Result.orThrough.md) | Runs an additional computation using the error value of a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md), but **returns the original failure** if the additional computation is successful. | ## Unwraps | Function | Description | | ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | | [unwrap](/byethrow/api/functions/Result.unwrap.md) | Extracts the success value from a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). | | [unwrapError](/byethrow/api/functions/Result.unwrapError.md) | Extracts the error value from a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). | ## Assertions | Function | Description | | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [assertFailure](/byethrow/api/functions/Result.assertFailure.md) | Asserts that a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md) is a [Failure](/byethrow/api/types/Result.Failure.md) and returns it. This function requires that the result's success type is `never`, meaning the result is guaranteed to be a [Failure](/byethrow/api/types/Result.Failure.md) at the type level. If the result is a [Success](/byethrow/api/types/Result.Success.md) at runtime, throws an error. | | [assertSuccess](/byethrow/api/functions/Result.assertSuccess.md) | Asserts that a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md) is a [Success](/byethrow/api/types/Result.Success.md) and returns it. This function requires that the result's error type is `never`, meaning the result is guaranteed to be a [Success](/byethrow/api/types/Result.Success.md) at the type level. If the result is a [Failure](/byethrow/api/types/Result.Failure.md) at runtime, throws an error. | ## Type Guards | Function | Description | | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | [isFailure](/byethrow/api/functions/Result.isFailure.md) | Type guard to check if a [Result](/byethrow/api/types/Result.Result.md) is a [Failure](/byethrow/api/types/Result.Failure.md). | | [isResult](/byethrow/api/functions/Result.isResult.md) | Type guard to check if a value is a [Result](/byethrow/api/types/Result.Result.md). | | [isSuccess](/byethrow/api/functions/Result.isSuccess.md) | Type guard to check if a [Result](/byethrow/api/types/Result.Result.md) is a [Success](/byethrow/api/types/Result.Success.md). | ## Utilities | Function | Description | | ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [collect](/byethrow/api/functions/Result.collect.md) | Processes multiple [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md) values into a single result. If all results are [Success](/byethrow/api/types/Result.Success.md), returns a [Success](/byethrow/api/types/Result.Success.md) containing all values. If any result is a [Failure](/byethrow/api/types/Result.Failure.md), returns a [Failure](/byethrow/api/types/Result.Failure.md) containing an array of all errors. | | [parse](/byethrow/api/functions/Result.parse.md) | Parses a value using a [Standard Schema](https://github.com/standard-schema/standard-schema) compatible schema. Returns a [Result](/byethrow/api/types/Result.Result.md) with the parsed value on success or validation errors on failure. | | [pipe](/byethrow/api/functions/Result.pipe.md) | Applies a sequence of functions to a value, from left to right. | | [sequence](/byethrow/api/functions/Result.sequence.md) | Processes multiple [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md) values into a single result. If all results are [Success](/byethrow/api/types/Result.Success.md), returns a [Success](/byethrow/api/types/Result.Success.md) containing all values. If any result is a [Failure](/byethrow/api/types/Result.Failure.md), immediately stops processing and returns a [Failure](/byethrow/api/types/Result.Failure.md) with that single error. | --- url: /byethrow/api/types/Result.Failure.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Type Alias: Failure\ > **Failure**\<`E`> = `object` Represents a failed result. ## Example ```ts import { Result } from '@praha/byethrow'; const failure: Result.Failure = { type: 'Failure', error: 'Something went wrong', }; ``` ## Type Parameters ### E `E` The type of the error. ## Properties ### error > `readonly` **error**: `E` *** ### type > `readonly` **type**: `"Failure"` --- url: /byethrow/api/types/Result.InferFailure.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Type Alias: InferFailure\ > **InferFailure**\<`T`> = \[`T`] _extends_ \[(...`args`) => [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, infer U>] ? `U` : \[`T`] _extends_ \[[`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, infer U>] ? `U` : `never` Infers the [Failure](/byethrow/api/types/Result.Failure.md) value type `E` from a Result or a function returning a Result. ## Type Parameters ### T `T` A [ResultMaybeAsync](/byethrow/api/types/Result.ResultMaybeAsync.md) type or a function returning it. ## Examples **From a result object** ```ts import { Result } from '@praha/byethrow'; type R = Result.Result; type ErrorValue = Result.InferFailure; // string ``` **From a function** ```ts import { Result } from '@praha/byethrow'; const fn = () => Promise.resolve({ type: 'Failure', error: new Error() } as const); type ErrorValue = Result.InferFailure; // Error ``` --- url: /byethrow/api/types/Result.InferSuccess.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Type Alias: InferSuccess\ > **InferSuccess**\<`T`> = \[`T`] _extends_ \[(...`args`) => [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\] ? `U` : \[`T`] _extends_ \[[`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\] ? `U` : `never` Infers the [Success](/byethrow/api/types/Result.Success.md) value type `T` from a Result or a function returning a Result. ## Type Parameters ### T `T` A [ResultMaybeAsync](/byethrow/api/types/Result.ResultMaybeAsync.md) type or a function returning it. ## Examples **From a result object** ```ts import { Result } from '@praha/byethrow'; type R = Result.Result; type SuccessValue = Result.InferSuccess; // number ``` **From a function** ```ts import { Result } from '@praha/byethrow'; const fn = () => Promise.resolve({ type: 'Success', value: 123 } as const); type SuccessValue = Result.InferSuccess; // number ``` --- url: /byethrow/api/types/Result.Result.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Type Alias: Result\ > **Result**\<`T`, `E`> = [`Success`](/byethrow/api/types/Result.Success.md)\<`T`> | [`Failure`](/byethrow/api/types/Result.Failure.md)\<`E`> A union type representing either a success or a failure. ## Type Parameters ### T `T` The type of the [Success](/byethrow/api/types/Result.Success.md) value. ### E `E` The type of the [Failure](/byethrow/api/types/Result.Failure.md) value. ## Example ```ts import { Result } from '@praha/byethrow'; const doSomething = (): Result.Result => { return Math.random() > 0.5 ? { type: 'Success', value: 10 } : { type: 'Failure', error: 'Oops' }; }; ``` --- url: /byethrow/api/types/Result.ResultAsync.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Type Alias: ResultAsync\ > **ResultAsync**\<`T`, `E`> = `Promise`\<[`Result`](/byethrow/api/types/Result.Result.md)\<`T`, `E`>> An asynchronous variant of [Result](/byethrow/api/types/Result.Result.md), wrapped in a `Promise`. ## Type Parameters ### T `T` The type of the [Success](/byethrow/api/types/Result.Success.md) value. ### E `E` The type of the [Failure](/byethrow/api/types/Result.Failure.md) value. ## Example ```ts import { Result } from '@praha/byethrow'; const fetchData = async (): Result.ResultAsync => { try { const data = await fetch('...'); return { type: 'Success', value: await data.text() }; } catch (err) { return { type: 'Failure', error: err as Error }; } }; ``` --- url: /byethrow/api/types/Result.ResultFor.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Type Alias: ResultFor\ > **ResultFor**\<`R`, `T`, `E`> = `true` _extends_ `HasPromise`\<`R`> ? [`ResultAsync`](/byethrow/api/types/Result.ResultAsync.md)\<`T`, `E`> : [`Result`](/byethrow/api/types/Result.Result.md)\<`T`, `E`> Resolves to the appropriate Result type (sync or async) based on the input type. Typically used to conditionally infer return types based on whether the original computation was async. ## Type Parameters ### R `R` The reference type to inspect for a Promise. ### T `T` The type of the [Success](/byethrow/api/types/Result.Success.md) value. ### E `E` The type of the [Failure](/byethrow/api/types/Result.Failure.md) value. ## Examples **With a Promise-returning function** ```ts import { Result } from '@praha/byethrow'; type R = Result.ResultAsync; type Output = Result.ResultFor; // Result.ResultAsync ``` **With a non-Promise-returning function** ```ts import { Result } from '@praha/byethrow'; type R = Result.Result; type Output = Result.ResultFor; // Result.Result ``` --- url: /byethrow/api/types/Result.ResultMaybeAsync.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Type Alias: ResultMaybeAsync\ > **ResultMaybeAsync**\<`T`, `E`> = [`Result`](/byethrow/api/types/Result.Result.md)\<`T`, `E`> | `Promise`\<[`Result`](/byethrow/api/types/Result.Result.md)\<`T`, `E`>> A result that may be either synchronous or asynchronous. ## Type Parameters ### T `T` The type of the [Success](/byethrow/api/types/Result.Success.md) value. ### E `E` The type of the [Failure](/byethrow/api/types/Result.Failure.md) value. ## Examples **Synchronous Case** ```ts import { Result } from '@praha/byethrow'; const result: Result.ResultMaybeAsync = { type: 'Success', value: 10 }; ``` **Asynchronous Case** ```ts import { Result } from '@praha/byethrow'; const result: Result.ResultMaybeAsync = Promise.resolve({ type: 'Failure', error: 'error' }); ``` --- url: /byethrow/api/types/Result.Success.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Type Alias: Success\ > **Success**\<`T`> = `object` Represents a successful result. ## Example ```ts import { Result } from '@praha/byethrow'; const success: Result.Success = { type: 'Success', value: 42, }; ``` ## Type Parameters ### T `T` The type of the successful value. ## Properties ### type > `readonly` **type**: `"Success"` *** ### value > `readonly` **value**: `T` --- url: /byethrow/api/functions/Result.andThen.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: andThen() Chains the next computation using the success value of a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). If the original result is a [Failure](/byethrow/api/types/Result.Failure.md), it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is. - `Success(a)`: `fn(a)` returns `Success(b)` → `Success(b)` - `Success(a)`: `fn(a)` returns `Failure(f)` → `Failure(f)` - `Failure(e)`: `fn` is not called → `Failure(e)` ## Type Param **R1** The input [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). ## Type Param **R2** The result type returned by `fn`. ## Examples **Success Case** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.succeed(3), Result.andThen((x) => Result.succeed(x * 2)), ); // { type: 'Success', value: 6 } ``` **Failure Case (input is a Failure)** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.fail('error'), Result.andThen((x) => Result.succeed(x * 2)), ); // result: { type: 'Failure', error: 'error' } ``` **Failure Case (function returns a Failure)** ```ts 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' } ``` ## See [pipe](/byethrow/api/functions/Result.pipe.md) - It is recommended to use this function with the [pipe](/byethrow/api/functions/Result.pipe.md) function for better readability and composability. ## Call Signature > **andThen**\<`R1`, `R2`>(`fn`): (`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `R2`, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R2`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`> | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R2`>> ### Type Parameters #### R1 `R1` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> #### R2 `R2` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> ### Parameters #### fn (`a`) => `R2` ### Returns (`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `R2`, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R2`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`> | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R2`>> ## Call Signature > **andThen**\<`F`>(`fn`): \<`R1`>(`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `ReturnType`\<`F`>, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`F`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`> | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`F`>> ### Type Parameters #### F `F` _extends_ (`a`) => [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> ### Parameters #### fn `F` ### Returns \<`R1`>(`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `ReturnType`\<`F`>, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`F`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`> | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`F`>> --- url: /byethrow/api/functions/Result.andThrough.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: andThrough() Runs an additional computation using the success value of a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md), but **returns the original result** if the additional computation is successful. If either the original result or the side effect result is a [Failure](/byethrow/api/types/Result.Failure.md), that failure is returned. Useful for running validations or side effects without altering the main result on success. - `Success(a)`: `fn(a)` returns `Success(b)` → `Success(a)` - `Success(a)`: `fn(a)` returns `Failure(f)` → `Failure(f)` - `Failure(e)`: `fn` is not called → `Failure(e)` ## Type Param **R1** The input [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). ## Type Param **R2** The result type returned by `fn`. ## Examples **Success Case** ```ts 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 } ``` **Failure Case (input is a Failure)** ```ts 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' } ``` **Failure Case (function returns a Failure)** ```ts 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' } ``` ## See [pipe](/byethrow/api/functions/Result.pipe.md) - It is recommended to use this function with the [pipe](/byethrow/api/functions/Result.pipe.md) function for better readability and composability. ## Call Signature > **andThrough**\<`R1`, `R2`>(`fn`): (`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `R2`, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`> | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R2`>> ### Type Parameters #### R1 `R1` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> #### R2 `R2` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> ### Parameters #### fn (`a`) => `R2` ### Returns (`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `R2`, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`> | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R2`>> ## Call Signature > **andThrough**\<`F`>(`fn`): \<`R1`>(`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `ReturnType`\<`F`>, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`> | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`F`>> ### Type Parameters #### F `F` _extends_ (`a`) => [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> ### Parameters #### fn `F` ### Returns \<`R1`>(`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `ReturnType`\<`F`>, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`> | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`F`>> --- url: /byethrow/api/functions/Result.assertFailure.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: assertFailure() > **assertFailure**\<`R`>(`result`): `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<[`Failure`](/byethrow/api/types/Result.Failure.md)\<[`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`>>> : [`Failure`](/byethrow/api/types/Result.Failure.md)\<[`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`>> Asserts that a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md) is a [Failure](/byethrow/api/types/Result.Failure.md) and returns it. This function requires that the result's success type is `never`, meaning the result is guaranteed to be a [Failure](/byethrow/api/types/Result.Failure.md) at the type level. If the result is a [Success](/byethrow/api/types/Result.Success.md) at runtime, throws an error. ## Type Parameters ### R `R` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`never`, `any`> The result type that extends [ResultMaybeAsync](/byethrow/api/types/Result.ResultMaybeAsync.md) with `never` as the success type. ## Parameters ### result `R` The [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md) to assert as a [Failure](/byethrow/api/types/Result.Failure.md). The success type must be `never`. ## Returns `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<[`Failure`](/byethrow/api/types/Result.Failure.md)\<[`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`>>> : [`Failure`](/byethrow/api/types/Result.Failure.md)\<[`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`>> The [Failure](/byethrow/api/types/Result.Failure.md) result or a Promise of [Failure](/byethrow/api/types/Result.Failure.md) result. ## Throws If the result is a [Success](/byethrow/api/types/Result.Success.md) at runtime. ## Examples ```ts import { Result } from '@praha/byethrow'; const result = Result.fail('error'); const failure = Result.assertFailure(result); // failure: { type: 'Failure', error: 'error' } ``` **Type-safe usage after narrowing success type** ```ts import { Result } from '@praha/byethrow'; const getResult = (): Result.Result => Result.fail('error'); const value = Result.pipe( getResult(), Result.andThen(() => Result.fail('die')), // Success type becomes never Result.assertFailure, // Type-safe: success type is now never Result.unwrapError(), // Safe unwrap after assertion ); ``` ## See [unwrapError](/byethrow/api/functions/Result.unwrapError.md) - Use with `assertFailure` to safely unwrap error values. --- url: /byethrow/api/functions/Result.assertSuccess.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: assertSuccess() > **assertSuccess**\<`R`>(`result`): `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<[`Success`](/byethrow/api/types/Result.Success.md)\<[`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`>>> : [`Success`](/byethrow/api/types/Result.Success.md)\<[`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`>> Asserts that a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md) is a [Success](/byethrow/api/types/Result.Success.md) and returns it. This function requires that the result's error type is `never`, meaning the result is guaranteed to be a [Success](/byethrow/api/types/Result.Success.md) at the type level. If the result is a [Failure](/byethrow/api/types/Result.Failure.md) at runtime, throws an error. ## Type Parameters ### R `R` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `never`> The result type that extends [ResultMaybeAsync](/byethrow/api/types/Result.ResultMaybeAsync.md) with `never` as the error type. ## Parameters ### result `R` The [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md) to assert as a [Success](/byethrow/api/types/Result.Success.md). The error type must be `never`. ## Returns `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<[`Success`](/byethrow/api/types/Result.Success.md)\<[`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`>>> : [`Success`](/byethrow/api/types/Result.Success.md)\<[`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`>> The [Success](/byethrow/api/types/Result.Success.md) result or a Promise of [Success](/byethrow/api/types/Result.Success.md) result. ## Throws If the result is a [Failure](/byethrow/api/types/Result.Failure.md) at runtime. ## Examples ```ts import { Result } from '@praha/byethrow'; const result = Result.succeed(42); const success = Result.assertSuccess(result); // success: { type: 'Success', value: 42 } ``` **Type-safe usage after narrowing error type** ```ts import { Result } from '@praha/byethrow'; const getResult = (): Result.Result => Result.succeed(42); const value = Result.pipe( getResult(), Result.orElse(() => Result.succeed(0)), // Error type becomes never Result.assertSuccess, // Type-safe: error type is now never Result.unwrap(), // Safe unwrap after assertion ); ``` ## See [unwrap](/byethrow/api/functions/Result.unwrap.md) - Use with `assertSuccess` to safely unwrap success values. --- url: /byethrow/api/functions/Result.bind.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: bind() Chains another [Result](/byethrow/api/types/Result.Result.md)-producing computation and **merges its success value** into the existing object under the specified key. - If the original result is a [Failure](/byethrow/api/types/Result.Failure.md), it is returned as-is. - If the next result is a [Failure](/byethrow/api/types/Result.Failure.md), it is returned as-is. - If both are [Success](/byethrow/api/types/Result.Success.md), a new object is returned by shallow-merging: the original success object and `{ [name]: nextSuccess }`. This is useful for building up objects in a compositional and type-safe way, especially in validation or data-fetching pipelines. - `Success({ a })`: `fn({ a })` returns `Success(b)` → `Success({ a, b })` - `Success({ a })`: `fn({ a })` returns `Failure(f)` → `Failure(f)` - `Failure(e)`: `fn` is not called → `Failure(e)` ## Type Param **N** The key to assign the result of the `fn` computation. ## Type Param **R1** The input [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). ## Type Param **R2** The result type returned by `fn`. ## Examples **Success Case** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.succeed({ name: 'Alice' }), Result.bind('age', (user) => Result.succeed(20)), ); // { type: 'Success', value: { name: 1, age: 20 } } ``` **Failure Case (input is a Failure)** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.fail('error'), Result.bind('age', (user) => Result.succeed(20)), ); // { type: 'Failure', error: 'error' } ``` **Failure Case (function returns a Failure)** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.succeed({ name: 'Alice' }), Result.bind('age', (user) => Result.fail('error')), ); // { type: 'Failure', error: 'error' } ``` ## See [pipe](/byethrow/api/functions/Result.pipe.md) - It is recommended to use this function with the [pipe](/byethrow/api/functions/Result.pipe.md) function for better readability and composability. ## Call Signature > **bind**\<`N`, `R1`, `R2`>(`name`, `fn`): (`result`) => [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`> _extends_ `object` ? [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `R2`, \{ \[K in string | number | symbol]: K extends Exclude\ ? InferSuccess\[K] : InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`> | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R2`>> : `unknown` ### Type Parameters #### N `N` _extends_ `string` #### R1 `R1` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> #### R2 `R2` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> ### Parameters #### name `N` #### fn (`a`) => `R2` ### Returns (`result`) => [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`> _extends_ `object` ? [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `R2`, \{ \[K in string | number | symbol]: K extends Exclude\ ? InferSuccess\[K] : InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`> | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R2`>> : `unknown` ## Call Signature > **bind**\<`N`, `F`>(`name`, `fn`): \<`R1`>(`result`) => `Parameters`\<`F`>\[`0`] _extends_ `object` ? [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `ReturnType`\<`F`>, \{ \[K in string | number | symbol]: K extends Exclude\ ? any\[any]\[K] : InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`> | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`F`>> : `unknown` ### Type Parameters #### N `N` _extends_ `string` #### F `F` _extends_ (`a`) => [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> ### Parameters #### name `N` #### fn `F` ### Returns \<`R1`>(`result`) => `Parameters`\<`F`>\[`0`] _extends_ `object` ? [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `ReturnType`\<`F`>, \{ \[K in string | number | symbol]: K extends Exclude\ ? any\[any]\[K] : InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`> | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`F`>> : `unknown` --- url: /byethrow/api/functions/Result.collect.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: collect() Processes multiple [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md) values into a single result. If all results are [Success](/byethrow/api/types/Result.Success.md), returns a [Success](/byethrow/api/types/Result.Success.md) containing all values. If any result is a [Failure](/byethrow/api/types/Result.Failure.md), returns a [Failure](/byethrow/api/types/Result.Failure.md) containing an array of all errors. Unlike [sequence](/byethrow/api/functions/Result.sequence.md), which stops at the first error and returns only that error, `collect` processes all results and collects all errors. - `[Success(a), Success(b), Success(c)]`: all values are gathered → `Success([a, b, c])` - `[Success(a), Failure(e), Failure(f)]`: all errors are gathered → `Failure([e, f])` ## Type Param **X** The input type (object or array of Results). ## Examples **Object of Results (all succeed)** ```ts import { Result } from '@praha/byethrow'; const result = Result.collect({ name: Result.succeed('Alice'), age: Result.succeed(20), }); // { type: 'Success', value: { name: 'Alice', age: 20 } } ``` **Object of Results (some fail)** ```ts import { Result } from '@praha/byethrow'; const result = Result.collect({ name: Result.succeed('Alice'), age: Result.fail('Invalid age'), }); // { type: 'Failure', error: ['Invalid age'] } ``` **Array of Results (all succeed)** ```ts import { Result } from '@praha/byethrow'; const result = Result.collect([ Result.succeed(1), Result.succeed(2), Result.succeed(3), ]); // { type: 'Success', value: [1, 2, 3] } ``` **Array of Results (some fail)** ```ts import { Result } from '@praha/byethrow'; const result = Result.collect([ Result.succeed(1), Result.fail('error1'), Result.fail('error2'), ]); // { type: 'Failure', error: ['error1', 'error2'] } ``` **Using a mapper function (all succeed)** ```ts import { Result } from '@praha/byethrow'; const result = Result.collect(['1', '2', '3'], (value) => { const number = Number(value); return Number.isNaN(number) ? Result.fail(`Invalid number: ${value}`) : Result.succeed(number); }); // { type: 'Success', value: [1, 2, 3] } ``` **Using a mapper function (some fail)** ```ts import { Result } from '@praha/byethrow'; const result = Result.collect(['1', 'invalid', '3'], (value) => { const number = Number(value); return Number.isNaN(number) ? Result.fail(`Invalid number: ${value}`) : Result.succeed(number); }); // { type: 'Failure', error: ['Invalid number: invalid'] } ``` ## Call Signature > **collect**\<`X`>(`x`): [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`X`\[keyof `X`], \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`X`\[keyof `X`]>\[]> ### Type Parameters #### X `X` _extends_ `Record`\<`string`, [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`>> ### Parameters #### x `X` ### Returns [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`X`\[keyof `X`], \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`X`\[keyof `X`]>\[]> ## Call Signature > **collect**\<`X`>(`x`): [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`X`\[`number`], \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`X`\[`number`]>\[]> ### Type Parameters #### X `X` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`>\[] ### Parameters #### x `X` ### Returns [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`X`\[`number`], \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`X`\[`number`]>\[]> ## Call Signature > **collect**\<`X`>(`x`): [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`X`\[`number`], \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`X`\[`number`]>\[]> ### Type Parameters #### X `X` _extends_ readonly [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`>\[] ### Parameters #### x `X` ### Returns [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`X`\[`number`], \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`X`\[`number`]>\[]> ## Call Signature > **collect**\<`X`, `Fn`>(`x`, `fn`): [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`ReturnType`\<`Fn`>, \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`Fn`>\[]> ### Type Parameters #### X `X` _extends_ `unknown`\[] #### Fn `Fn` _extends_ (`value`) => [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> ### Parameters #### x `X` #### fn `Fn` ### Returns [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`ReturnType`\<`Fn`>, \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`Fn`>\[]> ## Call Signature > **collect**\<`X`, `Fn`>(`x`, `fn`): [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`ReturnType`\<`Fn`>, \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`Fn`>\[]> ### Type Parameters #### X `X` _extends_ readonly `unknown`\[] #### Fn `Fn` _extends_ (`value`) => [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> ### Parameters #### x `X` #### fn `Fn` ### Returns [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`ReturnType`\<`Fn`>, \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`Fn`>\[]> --- url: /byethrow/api/functions/Result.do.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: do() > **do**(): [`Result`](/byethrow/api/types/Result.Result.md)\<\{ }, `never`> Alias for `succeed({})`. Commonly used as a neutral base value in functional chains or monadic pipelines. ## Returns [`Result`](/byethrow/api/types/Result.Result.md)\<\{ }, `never`> ## Example ```ts import { Result } from '@praha/byethrow'; const result = Result.do(); // Result.Result<{}, never> ``` --- url: /byethrow/api/functions/Result.fail.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: fail() Creates a [Failure](/byethrow/api/types/Result.Failure.md) result from a given error. Passing a `Promise` is allowed, but it is recommended to `await` it before passing to `fail`. ## Type Param **E** The type of the error to wrap. ## Examples **Synchronous Usage** ```ts import { Result } from '@praha/byethrow'; const result = Result.fail('Something went wrong'); // Result.Result ``` **With No Value** ```ts import { Result } from '@praha/byethrow'; const result = Result.fail(); // Result.Result ``` ## See - [collect](/byethrow/api/functions/Result.collect.md) - For collect multiple Results into a single Result. - [sequence](/byethrow/api/functions/Result.sequence.md) - For sequence multiple Results into a single Result. ## Call Signature > **fail**(): [`Result`](/byethrow/api/types/Result.Result.md)\<`never`, `void`> ### Returns [`Result`](/byethrow/api/types/Result.Result.md)\<`never`, `void`> ## Call Signature > **fail**\<`E`>(`error`): [`Result`](/byethrow/api/types/Result.Result.md)\<`never`, `E`> ### Type Parameters #### E `E` ### Parameters #### error `E` ### Returns [`Result`](/byethrow/api/types/Result.Result.md)\<`never`, `E`> --- url: /byethrow/api/functions/Result.fn.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: fn() Wraps a function that may throw and returns a new function that returns a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). You can use either a custom `catch` handler or rely on the `safe: true` option to assume the function cannot throw. - `a`: `try(...args)` returns `a` → `Success(a)` - `throw x`: `catch(x)` returns `e` → `Failure(e)` ## Type Param **T** The function type to execute (sync or async) or a Promise type. ## Type Param **E** The error type to return if `catch` is used. ## Examples **Sync try-catch** ```ts 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 ``` **Sync safe** ```ts import { Result } from '@praha/byethrow'; const fn = Result.fn({ safe: true, try: (x: number) => x + 1, }); const result = fn(1); // Result.Result ``` **Async try-catch** ```ts 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 ``` **Async safe** ```ts import { Result } from '@praha/byethrow'; const fn = Result.fn({ safe: true, try: async () => await Promise.resolve('ok'), }); const result = await fn(); // Result.ResultAsync ``` ## Call Signature > **fn**\<`T`, `E`>(`options`): (...`args`) => [`ResultAsync`](/byethrow/api/types/Result.ResultAsync.md)\<`Awaited`\<`ReturnType`\<`T`>>, `E`> ### Type Parameters #### T `T` _extends_ (...`args`) => `Promise`\<`any`> #### E `E` ### Parameters #### options ##### catch (`error`) => `E` ##### try `T` ### Returns (...`args`) => [`ResultAsync`](/byethrow/api/types/Result.ResultAsync.md)\<`Awaited`\<`ReturnType`\<`T`>>, `E`> ## Call Signature > **fn**\<`T`>(`options`): (...`args`) => [`ResultAsync`](/byethrow/api/types/Result.ResultAsync.md)\<`Awaited`\<`ReturnType`\<`T`>>, `never`> ### Type Parameters #### T `T` _extends_ (...`args`) => `Promise`\<`any`> ### Parameters #### options ##### safe `true` ##### try `T` ### Returns (...`args`) => [`ResultAsync`](/byethrow/api/types/Result.ResultAsync.md)\<`Awaited`\<`ReturnType`\<`T`>>, `never`> ## Call Signature > **fn**\<`T`, `E`>(`options`): (...`args`) => [`Result`](/byethrow/api/types/Result.Result.md)\<`ReturnType`\<`T`>, `E`> ### Type Parameters #### T `T` _extends_ (...`args`) => `any` #### E `E` ### Parameters #### options ##### catch (`error`) => `E` ##### try `T` ### Returns (...`args`) => [`Result`](/byethrow/api/types/Result.Result.md)\<`ReturnType`\<`T`>, `E`> ## Call Signature > **fn**\<`T`>(`options`): (...`args`) => [`Result`](/byethrow/api/types/Result.Result.md)\<`ReturnType`\<`T`>, `never`> ### Type Parameters #### T `T` _extends_ (...`args`) => `any` ### Parameters #### options ##### safe `true` ##### try `T` ### Returns (...`args`) => [`Result`](/byethrow/api/types/Result.Result.md)\<`ReturnType`\<`T`>, `never`> --- url: /byethrow/api/functions/Result.inspect.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: inspect() Executes a side effect function on the success value of a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md), without modifying the original result. This is useful for debugging, logging, or performing other side effects while maintaining the original value and error state. - `Success(a)`: `fn(a)` is called and its return value is ignored → `Success(a)` - `Failure(e)`: `fn` is not called → `Failure(e)` ## Type Param **R1** The input [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). ## Type Param **R2** The return type of the inspection function. ## Examples **Success Case** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.succeed(42), Result.inspect((value) => console.log('Debug:', value)), ); // Console output: "Debug: 42" // Result: { type: 'Success', value: 42 } ``` **Failure Case** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.fail('error'), Result.inspect((value) => console.log('Debug:', value)), ); // No console output // Result: { type: 'Failure', error: 'error' } ``` ## See [pipe](/byethrow/api/functions/Result.pipe.md) - It is recommended to use this function with the [pipe](/byethrow/api/functions/Result.pipe.md) function for better readability and composability. ## Call Signature > **inspect**\<`R1`, `R2`>(`fn`): (`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `R2`, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`>> ### Type Parameters #### R1 `R1` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> #### R2 `R2` ### Parameters #### fn (`a`) => `R2` ### Returns (`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `R2`, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`>> ## Call Signature > **inspect**\<`F`>(`fn`): \<`R1`>(`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `ReturnType`\<`F`>, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`>> ### Type Parameters #### F `F` _extends_ (`a`) => `unknown` ### Parameters #### fn `F` ### Returns \<`R1`>(`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `ReturnType`\<`F`>, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`>> --- url: /byethrow/api/functions/Result.inspectError.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: inspectError() Executes a side effect function on the error value of a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md), without modifying the original result. This is useful for debugging, logging, or performing other side effects while maintaining the original value and error state. - `Failure(e)`: `fn(e)` is called and its return value is ignored → `Failure(e)` - `Success(a)`: `fn` is not called → `Success(a)` ## Type Param **R1** The input [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). ## Type Param **R2** The return type of the inspection function. ## Examples **Failure Case** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.fail('error'), Result.inspectError((error) => console.log('Debug error:', error)), ); // Console output: "Debug error: error" // Result: { type: 'Failure', error: 'error' } ``` **Success Case** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.succeed(42), Result.inspectError((error) => console.log('Debug error:', error)), ); // No console output // Result: { type: 'Success', value: 42 } ``` ## See [pipe](/byethrow/api/functions/Result.pipe.md) - It is recommended to use this function with the [pipe](/byethrow/api/functions/Result.pipe.md) function for better readability and composability. ## Call Signature > **inspectError**\<`R1`, `R2`>(`fn`): (`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `R2`, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`>> ### Type Parameters #### R1 `R1` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> #### R2 `R2` ### Parameters #### fn (`a`) => `R2` ### Returns (`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `R2`, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`>> ## Call Signature > **inspectError**\<`F`>(`fn`): \<`R1`>(`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `ReturnType`\<`F`>, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`>> ### Type Parameters #### F `F` _extends_ (`a`) => `unknown` ### Parameters #### fn `F` ### Returns \<`R1`>(`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `ReturnType`\<`F`>, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`>> --- url: /byethrow/api/functions/Result.isFailure.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: isFailure() > **isFailure**\<`R`>(`result`): `result is Extract` Type guard to check if a [Result](/byethrow/api/types/Result.Result.md) is a [Failure](/byethrow/api/types/Result.Failure.md). ## Type Parameters ### R `R` _extends_ [`Result`](/byethrow/api/types/Result.Result.md)\<`unknown`, `unknown`> The type of the result to check. ## Parameters ### result `R` The [Result](/byethrow/api/types/Result.Result.md) to check. ## Returns `result is Extract` `true` if the result is a [Failure](/byethrow/api/types/Result.Failure.md), otherwise `false`. ## Example ```ts import { Result } from '@praha/byethrow'; const result: Result.Result = { type: 'Failure', error: 'Something went wrong' }; if (Result.isFailure(result)) { console.error(result.error); // Safe access to error } ``` --- url: /byethrow/api/functions/Result.isResult.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: isResult() > **isResult**\<`T`, `E`>(`result`): `result is Result` Type guard to check if a value is a [Result](/byethrow/api/types/Result.Result.md). ## Type Parameters ### T `T` The type of the success value. ### E `E` The type of the error value. ## Parameters ### result `unknown` The value to check. ## Returns `result is Result` `true` if the value is a [Result](/byethrow/api/types/Result.Result.md), otherwise `false`. ## Example ```ts import { Result } from '@praha/byethrow'; const value: unknown = { type: 'Success', value: 42 }; if (Result.isResult(value)) { // value is now typed as Result console.log(value.type); // 'Success' or 'Failure' } ``` --- url: /byethrow/api/functions/Result.isSuccess.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: isSuccess() > **isSuccess**\<`R`>(`result`): `result is Extract` Type guard to check if a [Result](/byethrow/api/types/Result.Result.md) is a [Success](/byethrow/api/types/Result.Success.md). ## Type Parameters ### R `R` _extends_ [`Result`](/byethrow/api/types/Result.Result.md)\<`unknown`, `unknown`> The type of the result to check. ## Parameters ### result `R` The [Result](/byethrow/api/types/Result.Result.md) to check. ## Returns `result is Extract` `true` if the result is a [Success](/byethrow/api/types/Result.Success.md), otherwise `false`. ## Example ```ts import { Result } from '@praha/byethrow'; const result: Result.Result = { type: 'Success', value: 10 }; if (Result.isSuccess(result)) { console.log(result.value); // Safe access to value } ``` --- url: /byethrow/api/functions/Result.let.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: let() Computes a **plain value** from the current success object and attaches it to the existing object under the specified key. - If the original result is a [Failure](/byethrow/api/types/Result.Failure.md), it is returned as-is. - If the original result is a [Success](/byethrow/api/types/Result.Success.md), a new object is returned by shallow-merging: the original success object and `{ [name]: fn(value) }`. This is the companion of [bind](/byethrow/api/functions/Result.bind.md) for derivations that cannot fail. `fn` is expected to be a pure, synchronous computation. Use [bind](/byethrow/api/functions/Result.bind.md) instead when the value comes from a fallible or asynchronous computation. - `Success({ a })`: `fn({ a })` returns `b` → `Success({ a, b })` - `Failure(e)`: `fn` is not called → `Failure(e)` ## Type Param **N** The key to assign the result of the `fn` computation. ## Type Param **R1** The input [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). ## Type Param **T2** The value type returned by `fn`. ## Examples **Success Case** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.succeed({ firstName: 'Alice', lastName: 'Smith' }), Result.let('fullName', ({ firstName, lastName }) => `${firstName} ${lastName}`), ); // { type: 'Success', value: { firstName: 'Alice', lastName: 'Smith', fullName: 'Alice Smith' } } ``` **Failure Case** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.fail('error'), Result.let('fullName', ({ firstName, lastName }) => `${firstName} ${lastName}`), ); // { type: 'Failure', error: 'error' } ``` **Combined with bind** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.do(), Result.bind('x', () => Result.succeed(1)), Result.bind('y', () => Result.succeed(2)), Result.let('z', ({ x, y }) => x + y), ); // { type: 'Success', value: { x: 1, y: 2, z: 3 } } ``` ## See - [pipe](/byethrow/api/functions/Result.pipe.md) - It is recommended to use this function with the [pipe](/byethrow/api/functions/Result.pipe.md) function for better readability and composability. - [bind](/byethrow/api/functions/Result.bind.md) - Use this function instead when the value is computed by a [Result](/byethrow/api/types/Result.Result.md)-producing function. ## Call Signature > **let**\<`N`, `R1`, `T2`>(`name`, `fn`): (`result`) => [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`> _extends_ `object` ? [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1`, \{ \[K in string | number | symbol]: K extends Exclude\ ? InferSuccess\[K] : T2 }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`>> : `unknown` ### Type Parameters #### N `N` _extends_ `string` #### R1 `R1` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> #### T2 `T2` ### Parameters #### name `N` #### fn (`a`) => `T2` ### Returns (`result`) => [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`> _extends_ `object` ? [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1`, \{ \[K in string | number | symbol]: K extends Exclude\ ? InferSuccess\[K] : T2 }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`>> : `unknown` ## Call Signature > **let**\<`N`, `T1`, `T2`>(`name`, `fn`): \<`R1`>(`result`) => `T1` _extends_ `object` ? [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1`, \{ \[K in string | number | symbol]: K extends Exclude\ ? T1\[K] : T2 }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`>> : `unknown` ### Type Parameters #### N `N` _extends_ `string` #### T1 `T1` #### T2 `T2` ### Parameters #### name `N` #### fn (`a`) => `T2` ### Returns \<`R1`>(`result`) => `T1` _extends_ `object` ? [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1`, \{ \[K in string | number | symbol]: K extends Exclude\ ? T1\[K] : T2 }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`>> : `unknown` --- url: /byethrow/api/functions/Result.map.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: map() Applies a transformation function to the success value of a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). If the input is a [Failure](/byethrow/api/types/Result.Failure.md), it will be returned unchanged. - `Success(a)`: `fn(a)` returns `b` → `Success(b)` - `Failure(e)`: `fn` is not called → `Failure(e)` ## Type Param **R1** The input [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). ## Type Param **T2** The transformed success value type. ## Examples **Success Case** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.succeed(2), Result.map((x) => x * 10), ); // { type: 'Success', value: 20 } ``` **Failure Case (unchanged)** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.fail('error'), Result.map((x) => x * 10), ); // { type: 'Failure', error: 'error' } ``` ## See [pipe](/byethrow/api/functions/Result.pipe.md) - It is recommended to use this function with the [pipe](/byethrow/api/functions/Result.pipe.md) function for better readability and composability. ## Call Signature > **map**\<`R1`, `T2`>(`fn`): (`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1`, `T2`, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`>> ### Type Parameters #### R1 `R1` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> #### T2 `T2` ### Parameters #### fn (`a`) => `T2` ### Returns (`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1`, `T2`, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`>> ## Call Signature > **map**\<`T1`, `T2`>(`fn`): \<`R1`>(`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1`, `T2`, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`>> ### Type Parameters #### T1 `T1` #### T2 `T2` ### Parameters #### fn (`a`) => `T2` ### Returns \<`R1`>(`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1`, `T2`, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`>> --- url: /byethrow/api/functions/Result.mapError.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: mapError() Applies a transformation function to the error value of a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). If the input is a [Success](/byethrow/api/types/Result.Success.md), it will be returned unchanged. - `Failure(e)`: `fn(e)` returns `f` → `Failure(f)` - `Success(a)`: `fn` is not called → `Success(a)` ## Type Param **R1** The input [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). ## Type Param **E2** The transformed error value type. ## Examples **Failure Case (unchanged)** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.fail('NotFound'), Result.mapError((error) => new Error(error)), ); // { type: 'Failure', error: Error('NotFound') } ``` **Success Case (unchanged)** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.succeed(123), Result.mapError((error) => new Error(error)), ); // { type: 'Success', value: 123 } ``` ## See [pipe](/byethrow/api/functions/Result.pipe.md) - It is recommended to use this function with the [pipe](/byethrow/api/functions/Result.pipe.md) function for better readability and composability. ## Call Signature > **mapError**\<`R1`, `E2`>(`fn`): (`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1`, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, `E2`> ### Type Parameters #### R1 `R1` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> #### E2 `E2` ### Parameters #### fn (`a`) => `E2` ### Returns (`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1`, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, `E2`> ## Call Signature > **mapError**\<`E1`, `E2`>(`fn`): \<`R1`>(`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1`, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, `E2`> ### Type Parameters #### E1 `E1` #### E2 `E2` ### Parameters #### fn (`a`) => `E2` ### Returns \<`R1`>(`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1`, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, `E2`> --- url: /byethrow/api/functions/Result.orElse.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: orElse() Chains the next computation using the error value of a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). If the original result is a [Success](/byethrow/api/types/Result.Success.md), it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is. - `Failure(e)`: `fn(e)` returns `Success(b)` → `Success(b)` - `Failure(e)`: `fn(e)` returns `Failure(f)` → `Failure(f)` - `Success(a)`: `fn` is not called → `Success(a)` ## Type Param **R1** The input [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). ## Type Param **R2** The result type returned by `fn`. ## Examples **Success Case** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.succeed(42), Result.orElse((error) => Result.succeed(0)), ); // { type: 'Success', value: 42 } ``` **Failure Case (function returns a Success)** ```ts 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' } ``` **Failure Case (function returns a Failure)** ```ts 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' } ``` ## See [pipe](/byethrow/api/functions/Result.pipe.md) - It is recommended to use this function with the [pipe](/byethrow/api/functions/Result.pipe.md) function for better readability and composability. ## Call Signature > **orElse**\<`R1`, `R2`>(`fn`): (`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `R2`, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`> | [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R2`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R2`>> ### Type Parameters #### R1 `R1` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> #### R2 `R2` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> ### Parameters #### fn (`a`) => `R2` ### Returns (`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `R2`, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`> | [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R2`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R2`>> ## Call Signature > **orElse**\<`F`>(`fn`): \<`R1`>(`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `ReturnType`\<`F`>, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`> | [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`F`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`F`>> ### Type Parameters #### F `F` _extends_ (`a`) => [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> ### Parameters #### fn `F` ### Returns \<`R1`>(`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `ReturnType`\<`F`>, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`> | [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`F`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`F`>> --- url: /byethrow/api/functions/Result.orThrough.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: orThrough() Runs an additional computation using the error value of a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md), but **returns the original failure** if the additional computation is successful. If the original result is a [Success](/byethrow/api/types/Result.Success.md), it is returned immediately without running the function. If the original result is a [Failure](/byethrow/api/types/Result.Failure.md), the function is executed with the error value. If the function returns a [Success](/byethrow/api/types/Result.Success.md), the original failure is returned. If the function returns a [Failure](/byethrow/api/types/Result.Failure.md), that new failure is returned. Useful for running error recovery or fallback logic while preserving the original error on success. - `Failure(e)`: `fn(e)` returns `Success(b)` → `Failure(e)` - `Failure(e)`: `fn(e)` returns `Failure(f)` → `Failure(f)` - `Success(a)`: `fn` is not called → `Success(a)` ## Type Param **R1** The input [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). ## Type Param **R2** The result type returned by `fn`. ## Examples **Success Case** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.succeed(5), Result.orThrough((error) => { return Result.succeed(null); }), ); // { type: 'Success', value: 5 } ``` **Failure Case (function returns a Success)** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.fail('error'), Result.orThrough((error) => { console.log('Logging error:', error); return Result.succeed(null); }), ); // { type: 'Failure', error: 'error' } ``` **Failure Case (function returns a Failure)** ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( Result.fail('original error'), Result.orThrough((error) => { return Result.fail('new error'); }), ); // { type: 'Failure', error: 'new error' } ``` ## See [pipe](/byethrow/api/functions/Result.pipe.md) - It is recommended to use this function with the [pipe](/byethrow/api/functions/Result.pipe.md) function for better readability and composability. ## Call Signature > **orThrough**\<`R1`, `R2`>(`fn`): (`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `R2`, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`> | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R2`>> ### Type Parameters #### R1 `R1` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> #### R2 `R2` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> ### Parameters #### fn (`a`) => `R2` ### Returns (`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `R2`, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`> | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R2`>> ## Call Signature > **orThrough**\<`F`>(`fn`): \<`R1`>(`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `ReturnType`\<`F`>, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`> | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`F`>> ### Type Parameters #### F `F` _extends_ (`a`) => [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> ### Parameters #### fn `F` ### Returns \<`R1`>(`result`) => [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`R1` | `ReturnType`\<`F`>, [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R1`>, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R1`> | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`F`>> --- url: /byethrow/api/functions/Result.parse.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: parse() Parses a value using a [Standard Schema](https://github.com/standard-schema/standard-schema) compatible schema. Returns a [Result](/byethrow/api/types/Result.Result.md) with the parsed value on success or validation errors on failure. - `a`: the value matches the schema → `Success(a)` - `a`: the value does not match the schema → `Failure(issues)` ## Type Param **S** The Standard Schema V1 compatible schema type. ## Examples **Basic Usage** ```ts import { Result } from '@praha/byethrow'; import { z } from 'zod'; const schema = z.object({ name: z.string() }); const result = Result.parse(schema, { name: 'John' }); // Result.Result<{ name: string }, ReadonlyArray> ``` **Curried Usage** ```ts import { Result } from '@praha/byethrow'; import { z } from 'zod'; const schema = z.object({ name: z.string() }); const parser = Result.parse(schema); const result = parser({ name: 'John' }); // Result.Result<{ name: string }, ReadonlyArray> ``` ## Call Signature > **parse**\<`S`>(`schema`): (`value`) => [`Result`](/byethrow/api/types/Result.Result.md)\<`InferOutput`\<`S`>, readonly `Issue`\[]> ### Type Parameters #### S `S` _extends_ `StandardSchemaV1`\<`unknown`, `unknown`> ### Parameters #### schema `S` ### Returns (`value`) => [`Result`](/byethrow/api/types/Result.Result.md)\<`InferOutput`\<`S`>, readonly `Issue`\[]> ## Call Signature > **parse**\<`S`>(`schema`, `value`): [`Result`](/byethrow/api/types/Result.Result.md)\<`InferOutput`\<`S`>, readonly `Issue`\[]> ### Type Parameters #### S `S` _extends_ `StandardSchemaV1`\<`unknown`, `unknown`> ### Parameters #### schema `S` #### value `unknown` ### Returns [`Result`](/byethrow/api/types/Result.Result.md)\<`InferOutput`\<`S`>, readonly `Issue`\[]> --- url: /byethrow/api/functions/Result.pipe.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: pipe() 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`. ## Type Param **A** The initial input value type. ## Type Param **B-Z** Intermediate and final function return types. ## Param **value** The initial input value. ## Param **functions** Additional unary functions composing of the previous result. ## Example ```ts import { Result } from '@praha/byethrow'; const result = Result.pipe( 2, x => x + 1, x => x * 3, x => `Result: ${x}` ); // Result: 9 ``` ## Call Signature > **pipe**\<`A`>(`a`): `A` ### Type Parameters #### A `A` ### Parameters #### a `A` ### Returns `A` ## Call Signature > **pipe**\<`A`, `B`>(`a`, `ab`): `B` ### Type Parameters #### A `A` #### B `B` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` ### Returns `B` ## Call Signature > **pipe**\<`A`, `B`, `C`>(`a`, `ab`, `bc`): `C` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` ### Returns `C` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`>(`a`, `ab`, `bc`, `cd`): `D` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` ### Returns `D` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`>(`a`, `ab`, `bc`, `cd`, `de`): `E` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` ### Returns `E` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`): `F` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` ### Returns `F` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`): `G` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` ### Returns `G` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`): `H` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` ### Returns `H` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`, `hi`): `I` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` #### I `I` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` #### hi (`h`) => `I` ### Returns `I` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`, `hi`, `ij`): `J` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` #### I `I` = `never` #### J `J` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` #### hi (`h`) => `I` #### ij (`i`) => `J` ### Returns `J` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`, `K`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`, `hi`, `ij`, `jk`): `K` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` #### I `I` = `never` #### J `J` = `never` #### K `K` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` #### hi (`h`) => `I` #### ij (`i`) => `J` #### jk (`j`) => `K` ### Returns `K` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`, `K`, `L`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`, `hi`, `ij`, `jk`, `kl`): `L` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` #### I `I` = `never` #### J `J` = `never` #### K `K` = `never` #### L `L` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` #### hi (`h`) => `I` #### ij (`i`) => `J` #### jk (`j`) => `K` #### kl (`k`) => `L` ### Returns `L` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`, `K`, `L`, `M`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`, `hi`, `ij`, `jk`, `kl`, `lm`): `M` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` #### I `I` = `never` #### J `J` = `never` #### K `K` = `never` #### L `L` = `never` #### M `M` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` #### hi (`h`) => `I` #### ij (`i`) => `J` #### jk (`j`) => `K` #### kl (`k`) => `L` #### lm (`l`) => `M` ### Returns `M` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`, `K`, `L`, `M`, `N`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`, `hi`, `ij`, `jk`, `kl`, `lm`, `mn`): `N` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` #### I `I` = `never` #### J `J` = `never` #### K `K` = `never` #### L `L` = `never` #### M `M` = `never` #### N `N` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` #### hi (`h`) => `I` #### ij (`i`) => `J` #### jk (`j`) => `K` #### kl (`k`) => `L` #### lm (`l`) => `M` #### mn (`m`) => `N` ### Returns `N` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`, `K`, `L`, `M`, `N`, `O`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`, `hi`, `ij`, `jk`, `kl`, `lm`, `mn`, `no`): `O` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` #### I `I` = `never` #### J `J` = `never` #### K `K` = `never` #### L `L` = `never` #### M `M` = `never` #### N `N` = `never` #### O `O` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` #### hi (`h`) => `I` #### ij (`i`) => `J` #### jk (`j`) => `K` #### kl (`k`) => `L` #### lm (`l`) => `M` #### mn (`m`) => `N` #### no (`n`) => `O` ### Returns `O` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`, `K`, `L`, `M`, `N`, `O`, `P`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`, `hi`, `ij`, `jk`, `kl`, `lm`, `mn`, `no`, `op`): `P` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` #### I `I` = `never` #### J `J` = `never` #### K `K` = `never` #### L `L` = `never` #### M `M` = `never` #### N `N` = `never` #### O `O` = `never` #### P `P` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` #### hi (`h`) => `I` #### ij (`i`) => `J` #### jk (`j`) => `K` #### kl (`k`) => `L` #### lm (`l`) => `M` #### mn (`m`) => `N` #### no (`n`) => `O` #### op (`o`) => `P` ### Returns `P` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`, `K`, `L`, `M`, `N`, `O`, `P`, `Q`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`, `hi`, `ij`, `jk`, `kl`, `lm`, `mn`, `no`, `op`, `pq`): `Q` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` #### I `I` = `never` #### J `J` = `never` #### K `K` = `never` #### L `L` = `never` #### M `M` = `never` #### N `N` = `never` #### O `O` = `never` #### P `P` = `never` #### Q `Q` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` #### hi (`h`) => `I` #### ij (`i`) => `J` #### jk (`j`) => `K` #### kl (`k`) => `L` #### lm (`l`) => `M` #### mn (`m`) => `N` #### no (`n`) => `O` #### op (`o`) => `P` #### pq (`p`) => `Q` ### Returns `Q` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`, `K`, `L`, `M`, `N`, `O`, `P`, `Q`, `R`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`, `hi`, `ij`, `jk`, `kl`, `lm`, `mn`, `no`, `op`, `pq`, `qr`): `R` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` #### I `I` = `never` #### J `J` = `never` #### K `K` = `never` #### L `L` = `never` #### M `M` = `never` #### N `N` = `never` #### O `O` = `never` #### P `P` = `never` #### Q `Q` = `never` #### R `R` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` #### hi (`h`) => `I` #### ij (`i`) => `J` #### jk (`j`) => `K` #### kl (`k`) => `L` #### lm (`l`) => `M` #### mn (`m`) => `N` #### no (`n`) => `O` #### op (`o`) => `P` #### pq (`p`) => `Q` #### qr (`q`) => `R` ### Returns `R` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`, `K`, `L`, `M`, `N`, `O`, `P`, `Q`, `R`, `S`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`, `hi`, `ij`, `jk`, `kl`, `lm`, `mn`, `no`, `op`, `pq`, `qr`, `rs`): `S` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` #### I `I` = `never` #### J `J` = `never` #### K `K` = `never` #### L `L` = `never` #### M `M` = `never` #### N `N` = `never` #### O `O` = `never` #### P `P` = `never` #### Q `Q` = `never` #### R `R` = `never` #### S `S` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` #### hi (`h`) => `I` #### ij (`i`) => `J` #### jk (`j`) => `K` #### kl (`k`) => `L` #### lm (`l`) => `M` #### mn (`m`) => `N` #### no (`n`) => `O` #### op (`o`) => `P` #### pq (`p`) => `Q` #### qr (`q`) => `R` #### rs (`r`) => `S` ### Returns `S` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`, `K`, `L`, `M`, `N`, `O`, `P`, `Q`, `R`, `S`, `T`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`, `hi`, `ij`, `jk`, `kl`, `lm`, `mn`, `no`, `op`, `pq`, `qr`, `rs`, `st`): `T` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` #### I `I` = `never` #### J `J` = `never` #### K `K` = `never` #### L `L` = `never` #### M `M` = `never` #### N `N` = `never` #### O `O` = `never` #### P `P` = `never` #### Q `Q` = `never` #### R `R` = `never` #### S `S` = `never` #### T `T` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` #### hi (`h`) => `I` #### ij (`i`) => `J` #### jk (`j`) => `K` #### kl (`k`) => `L` #### lm (`l`) => `M` #### mn (`m`) => `N` #### no (`n`) => `O` #### op (`o`) => `P` #### pq (`p`) => `Q` #### qr (`q`) => `R` #### rs (`r`) => `S` #### st (`s`) => `T` ### Returns `T` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`, `K`, `L`, `M`, `N`, `O`, `P`, `Q`, `R`, `S`, `T`, `U`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`, `hi`, `ij`, `jk`, `kl`, `lm`, `mn`, `no`, `op`, `pq`, `qr`, `rs`, `st`, `tu`): `U` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` #### I `I` = `never` #### J `J` = `never` #### K `K` = `never` #### L `L` = `never` #### M `M` = `never` #### N `N` = `never` #### O `O` = `never` #### P `P` = `never` #### Q `Q` = `never` #### R `R` = `never` #### S `S` = `never` #### T `T` = `never` #### U `U` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` #### hi (`h`) => `I` #### ij (`i`) => `J` #### jk (`j`) => `K` #### kl (`k`) => `L` #### lm (`l`) => `M` #### mn (`m`) => `N` #### no (`n`) => `O` #### op (`o`) => `P` #### pq (`p`) => `Q` #### qr (`q`) => `R` #### rs (`r`) => `S` #### st (`s`) => `T` #### tu (`t`) => `U` ### Returns `U` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`, `K`, `L`, `M`, `N`, `O`, `P`, `Q`, `R`, `S`, `T`, `U`, `V`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`, `hi`, `ij`, `jk`, `kl`, `lm`, `mn`, `no`, `op`, `pq`, `qr`, `rs`, `st`, `tu`, `uv`): `V` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` #### I `I` = `never` #### J `J` = `never` #### K `K` = `never` #### L `L` = `never` #### M `M` = `never` #### N `N` = `never` #### O `O` = `never` #### P `P` = `never` #### Q `Q` = `never` #### R `R` = `never` #### S `S` = `never` #### T `T` = `never` #### U `U` = `never` #### V `V` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` #### hi (`h`) => `I` #### ij (`i`) => `J` #### jk (`j`) => `K` #### kl (`k`) => `L` #### lm (`l`) => `M` #### mn (`m`) => `N` #### no (`n`) => `O` #### op (`o`) => `P` #### pq (`p`) => `Q` #### qr (`q`) => `R` #### rs (`r`) => `S` #### st (`s`) => `T` #### tu (`t`) => `U` #### uv (`u`) => `V` ### Returns `V` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`, `K`, `L`, `M`, `N`, `O`, `P`, `Q`, `R`, `S`, `T`, `U`, `V`, `W`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`, `hi`, `ij`, `jk`, `kl`, `lm`, `mn`, `no`, `op`, `pq`, `qr`, `rs`, `st`, `tu`, `uv`, `vw`): `W` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` #### I `I` = `never` #### J `J` = `never` #### K `K` = `never` #### L `L` = `never` #### M `M` = `never` #### N `N` = `never` #### O `O` = `never` #### P `P` = `never` #### Q `Q` = `never` #### R `R` = `never` #### S `S` = `never` #### T `T` = `never` #### U `U` = `never` #### V `V` = `never` #### W `W` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` #### hi (`h`) => `I` #### ij (`i`) => `J` #### jk (`j`) => `K` #### kl (`k`) => `L` #### lm (`l`) => `M` #### mn (`m`) => `N` #### no (`n`) => `O` #### op (`o`) => `P` #### pq (`p`) => `Q` #### qr (`q`) => `R` #### rs (`r`) => `S` #### st (`s`) => `T` #### tu (`t`) => `U` #### uv (`u`) => `V` #### vw (`v`) => `W` ### Returns `W` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`, `K`, `L`, `M`, `N`, `O`, `P`, `Q`, `R`, `S`, `T`, `U`, `V`, `W`, `X`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`, `hi`, `ij`, `jk`, `kl`, `lm`, `mn`, `no`, `op`, `pq`, `qr`, `rs`, `st`, `tu`, `uv`, `vw`, `wx`): `X` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` #### I `I` = `never` #### J `J` = `never` #### K `K` = `never` #### L `L` = `never` #### M `M` = `never` #### N `N` = `never` #### O `O` = `never` #### P `P` = `never` #### Q `Q` = `never` #### R `R` = `never` #### S `S` = `never` #### T `T` = `never` #### U `U` = `never` #### V `V` = `never` #### W `W` = `never` #### X `X` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` #### hi (`h`) => `I` #### ij (`i`) => `J` #### jk (`j`) => `K` #### kl (`k`) => `L` #### lm (`l`) => `M` #### mn (`m`) => `N` #### no (`n`) => `O` #### op (`o`) => `P` #### pq (`p`) => `Q` #### qr (`q`) => `R` #### rs (`r`) => `S` #### st (`s`) => `T` #### tu (`t`) => `U` #### uv (`u`) => `V` #### vw (`v`) => `W` #### wx (`w`) => `X` ### Returns `X` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`, `K`, `L`, `M`, `N`, `O`, `P`, `Q`, `R`, `S`, `T`, `U`, `V`, `W`, `X`, `Y`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`, `hi`, `ij`, `jk`, `kl`, `lm`, `mn`, `no`, `op`, `pq`, `qr`, `rs`, `st`, `tu`, `uv`, `vw`, `wx`, `xy`): `Y` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` #### I `I` = `never` #### J `J` = `never` #### K `K` = `never` #### L `L` = `never` #### M `M` = `never` #### N `N` = `never` #### O `O` = `never` #### P `P` = `never` #### Q `Q` = `never` #### R `R` = `never` #### S `S` = `never` #### T `T` = `never` #### U `U` = `never` #### V `V` = `never` #### W `W` = `never` #### X `X` = `never` #### Y `Y` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` #### hi (`h`) => `I` #### ij (`i`) => `J` #### jk (`j`) => `K` #### kl (`k`) => `L` #### lm (`l`) => `M` #### mn (`m`) => `N` #### no (`n`) => `O` #### op (`o`) => `P` #### pq (`p`) => `Q` #### qr (`q`) => `R` #### rs (`r`) => `S` #### st (`s`) => `T` #### tu (`t`) => `U` #### uv (`u`) => `V` #### vw (`v`) => `W` #### wx (`w`) => `X` #### xy (`x`) => `Y` ### Returns `Y` ## Call Signature > **pipe**\<`A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`, `I`, `J`, `K`, `L`, `M`, `N`, `O`, `P`, `Q`, `R`, `S`, `T`, `U`, `V`, `W`, `X`, `Y`, `Z`>(`a`, `ab`, `bc`, `cd`, `de`, `ef`, `fg`, `gh`, `hi`, `ij`, `jk`, `kl`, `lm`, `mn`, `no`, `op`, `pq`, `qr`, `rs`, `st`, `tu`, `uv`, `vw`, `wx`, `xy`, `yz`): `Z` ### Type Parameters #### A `A` #### B `B` = `never` #### C `C` = `never` #### D `D` = `never` #### E `E` = `never` #### F `F` = `never` #### G `G` = `never` #### H `H` = `never` #### I `I` = `never` #### J `J` = `never` #### K `K` = `never` #### L `L` = `never` #### M `M` = `never` #### N `N` = `never` #### O `O` = `never` #### P `P` = `never` #### Q `Q` = `never` #### R `R` = `never` #### S `S` = `never` #### T `T` = `never` #### U `U` = `never` #### V `V` = `never` #### W `W` = `never` #### X `X` = `never` #### Y `Y` = `never` #### Z `Z` = `never` ### Parameters #### a `A` #### ab (`a`) => `B` #### bc (`b`) => `C` #### cd (`c`) => `D` #### de (`d`) => `E` #### ef (`e`) => `F` #### fg (`f`) => `G` #### gh (`g`) => `H` #### hi (`h`) => `I` #### ij (`i`) => `J` #### jk (`j`) => `K` #### kl (`k`) => `L` #### lm (`l`) => `M` #### mn (`m`) => `N` #### no (`n`) => `O` #### op (`o`) => `P` #### pq (`p`) => `Q` #### qr (`q`) => `R` #### rs (`r`) => `S` #### st (`s`) => `T` #### tu (`t`) => `U` #### uv (`u`) => `V` #### vw (`v`) => `W` #### wx (`w`) => `X` #### xy (`x`) => `Y` #### yz (`y`) => `Z` ### Returns `Z` --- url: /byethrow/api/functions/Result.sequence.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: sequence() Processes multiple [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md) values into a single result. If all results are [Success](/byethrow/api/types/Result.Success.md), returns a [Success](/byethrow/api/types/Result.Success.md) containing all values. If any result is a [Failure](/byethrow/api/types/Result.Failure.md), immediately stops processing and returns a [Failure](/byethrow/api/types/Result.Failure.md) with that single error. Unlike [collect](/byethrow/api/functions/Result.collect.md), which processes all results and collects all errors, `sequence` stops at the first error and returns only that error. - `[Success(a), Success(b), Success(c)]`: all values are gathered → `Success([a, b, c])` - `[Success(a), Failure(e), Failure(f)]`: the first error is returned → `Failure(e)` ## Type Param **X** The input type (object or array of Results). ## Examples **Object of Results (all succeed)** ```ts import { Result } from '@praha/byethrow'; const result = Result.sequence({ name: Result.succeed('Alice'), age: Result.succeed(20), }); // { type: 'Success', value: { name: 'Alice', age: 20 } } ``` **Object of Results (stops at first failure)** ```ts import { Result } from '@praha/byethrow'; const result = Result.sequence({ name: Result.succeed('Alice'), age: Result.fail('Invalid age'), }); // { type: 'Failure', error: 'Invalid age' } ``` **Array of Results (all succeed)** ```ts import { Result } from '@praha/byethrow'; const result = Result.sequence([ Result.succeed(1), Result.succeed(2), ]); // { type: 'Success', value: [1, 2, 3] } ``` **Array of Results (stops at first failure)** ```ts import { Result } from '@praha/byethrow'; const result = Result.sequence([ Result.succeed(1), Result.fail('error1'), ]); // { type: 'Failure', error: 'error1' } ``` **Using a mapper function (all succeed)** ```ts import { Result } from '@praha/byethrow'; const result = Result.sequence(['1', '2', '3'], (value) => { const number = Number(value); return Number.isNaN(number) ? Result.fail(`Invalid number: ${value}`) : Result.succeed(number); }); // { type: 'Success', value: [1, 2, 3] } ``` **Using a mapper function (stops at first failure)** ```ts import { Result } from '@praha/byethrow'; const result = Result.sequence(['1', 'invalid', '3'], (value) => { const number = Number(value); return Number.isNaN(number) ? Result.fail(`Invalid number: ${value}`) : Result.succeed(number); }); // { type: 'Failure', error: 'Invalid number: invalid' } ``` ## Call Signature > **sequence**\<`X`>(`x`): [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`X`\[keyof `X`], \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`X`\[keyof `X`]>> ### Type Parameters #### X `X` _extends_ `Record`\<`string`, [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`>> ### Parameters #### x `X` ### Returns [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`X`\[keyof `X`], \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`X`\[keyof `X`]>> ## Call Signature > **sequence**\<`X`>(`x`): [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`X`\[`number`], \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`X`\[`number`]>> ### Type Parameters #### X `X` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`>\[] ### Parameters #### x `X` ### Returns [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`X`\[`number`], \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`X`\[`number`]>> ## Call Signature > **sequence**\<`X`>(`x`): [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`X`\[`number`], \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`X`\[`number`]>> ### Type Parameters #### X `X` _extends_ readonly [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`>\[] ### Parameters #### x `X` ### Returns [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`X`\[`number`], \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`X`\[`number`]>> ## Call Signature > **sequence**\<`X`, `Fn`>(`x`, `fn`): [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`ReturnType`\<`Fn`>, \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`Fn`>> ### Type Parameters #### X `X` _extends_ `unknown`\[] #### Fn `Fn` _extends_ (`value`) => [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> ### Parameters #### x `X` #### fn `Fn` ### Returns [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`ReturnType`\<`Fn`>, \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`Fn`>> ## Call Signature > **sequence**\<`X`, `Fn`>(`x`, `fn`): [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`ReturnType`\<`Fn`>, \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`Fn`>> ### Type Parameters #### X `X` _extends_ readonly `unknown`\[] #### Fn `Fn` _extends_ (`value`) => [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> ### Parameters #### x `X` #### fn `Fn` ### Returns [`ResultFor`](/byethrow/api/types/Result.ResultFor.md)\<`ReturnType`\<`Fn`>, \{ \[K in string | number | symbol]: InferSuccess\ }, [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`Fn`>> --- url: /byethrow/api/functions/Result.succeed.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: succeed() Creates a [Success](/byethrow/api/types/Result.Success.md) result from a given value. Passing a `Promise` is allowed, but it is recommended to `await` it before passing to `succeed`. ## Type Param **T** The type of the value to wrap. ## Examples **Synchronous Usage** ```ts import { Result } from '@praha/byethrow'; const result = Result.succeed(42); // Result.Result<42, never> ``` **With No Value** ```ts import { Result } from '@praha/byethrow'; const result = Result.succeed(); // Result.Result ``` ## See - [collect](/byethrow/api/functions/Result.collect.md) - For collect multiple Results into a single Result. - [sequence](/byethrow/api/functions/Result.sequence.md) - For sequence multiple Results into a single Result. ## Call Signature > **succeed**(): [`Result`](/byethrow/api/types/Result.Result.md)\<`void`, `never`> ### Returns [`Result`](/byethrow/api/types/Result.Result.md)\<`void`, `never`> ## Call Signature > **succeed**\<`T`>(`value`): [`Result`](/byethrow/api/types/Result.Result.md)\<`T`, `never`> ### Type Parameters #### T `T` ### Parameters #### value `T` ### Returns [`Result`](/byethrow/api/types/Result.Result.md)\<`T`, `never`> --- url: /byethrow/api/functions/Result.try.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: try() Executes a function that may throw and wraps the result in a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). You can use either a custom `catch` handler or rely on the `safe: true` option to assume the function cannot throw. - `a`: `try()` returns `a` → `Success(a)` - `throw x`: `catch(x)` returns `e` → `Failure(e)` ## Type Param **T** The function type to execute (sync or async) or a Promise type. ## Type Param **E** The error type to return if `catch` is used. ## Examples **Sync try-catch** ```ts import { Result } from '@praha/byethrow'; const result = Result.try({ 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 ``` **Sync safe** ```ts import { Result } from '@praha/byethrow'; const result = Result.try({ safe: true, try: () => Math.random() + 1, }); // result is Result ``` **Async try-catch** ```ts import { Result } from '@praha/byethrow'; const result = Result.try({ try: () => fetch('/api/data'), catch: (error) => new Error('Fetch failed', { cause: error }), }); // result is ResultAsync ``` **Async safe** ```ts import { Result } from '@praha/byethrow'; const result = Result.try({ safe: true, try: () => Promise.resolve('ok'), }); // result is ResultAsync ``` ## Call Signature > **try**\<`T`, `E`>(`options`): [`ResultAsync`](/byethrow/api/types/Result.ResultAsync.md)\<`Awaited`\<`ReturnType`\<`T`>>, `E`> ### Type Parameters #### T `T` _extends_ () => `Promise`\<`any`> #### E `E` ### Parameters #### options ##### catch (`error`) => `E` ##### try `T` ### Returns [`ResultAsync`](/byethrow/api/types/Result.ResultAsync.md)\<`Awaited`\<`ReturnType`\<`T`>>, `E`> ## Call Signature > **try**\<`T`>(`options`): [`ResultAsync`](/byethrow/api/types/Result.ResultAsync.md)\<`Awaited`\<`ReturnType`\<`T`>>, `never`> ### Type Parameters #### T `T` _extends_ () => `Promise`\<`any`> ### Parameters #### options ##### safe `true` ##### try `T` ### Returns [`ResultAsync`](/byethrow/api/types/Result.ResultAsync.md)\<`Awaited`\<`ReturnType`\<`T`>>, `never`> ## Call Signature > **try**\<`T`, `E`>(`options`): [`Result`](/byethrow/api/types/Result.Result.md)\<`ReturnType`\<`T`>, `E`> ### Type Parameters #### T `T` _extends_ () => `any` #### E `E` ### Parameters #### options ##### catch (`error`) => `E` ##### try `T` ### Returns [`Result`](/byethrow/api/types/Result.Result.md)\<`ReturnType`\<`T`>, `E`> ## Call Signature > **try**\<`T`>(`options`): [`Result`](/byethrow/api/types/Result.Result.md)\<`ReturnType`\<`T`>, `never`> ### Type Parameters #### T `T` _extends_ () => `any` ### Parameters #### options ##### safe `true` ##### try `T` ### Returns [`Result`](/byethrow/api/types/Result.Result.md)\<`ReturnType`\<`T`>, `never`> --- url: /byethrow/api/functions/Result.unwrap.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: unwrap() Extracts the success value from a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). If the input is a [Failure](/byethrow/api/types/Result.Failure.md), it will throw the error or return the default value if provided. - `Success(a)`: `a` is returned → `a` - `Failure(e)`: `e` is thrown if no default value is given → `throw e` - `Failure(e)`: the default value `d` is returned → `d` ## Type Param **R** The input [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). ## Type Param **T** The default value type (optional). ## Examples **Success Case (without default)** ```ts import { Result } from '@praha/byethrow'; const result = Result.succeed(42); const value = Result.unwrap(result); // 42 ``` **Success Case (with default)** ```ts import { Result } from '@praha/byethrow'; const result = Result.succeed(42); const value = Result.unwrap(result, 0); // 42 ``` **Failure Case (without default) - throws error** ```ts import { Result } from '@praha/byethrow'; const result = Result.fail('error'); Result.unwrap(result); // throws 'error' ``` **Failure Case (with default)** ```ts import { Result } from '@praha/byethrow'; const result = Result.fail('error'); const value = Result.unwrap(result, 0); // 0 ``` ## See [assertSuccess](/byethrow/api/functions/Result.assertSuccess.md) - When used with [assertSuccess](/byethrow/api/functions/Result.assertSuccess.md), you can safely unwrap the [Result](/byethrow/api/types/Result.Result.md). ## Call Signature > **unwrap**\<`R`>(`result`): `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<[`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`>> : [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`> ### Type Parameters #### R `R` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> ### Parameters #### result `R` ### Returns `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<[`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`>> : [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`> ## Call Signature > **unwrap**\<`R`, `T`>(`result`, `defaultValue`): `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<`T` | [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`>> : `T` | [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`> ### Type Parameters #### R `R` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> #### T `T` ### Parameters #### result `R` #### defaultValue `T` ### Returns `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<`T` | [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`>> : `T` | [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`> ## Call Signature > **unwrap**\<`R`>(): (`result`) => `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<[`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`>> : [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`> ### Type Parameters #### R `R` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> ### Returns (`result`) => `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<[`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`>> : [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`> ## Call Signature > **unwrap**\<`R`, `T`>(`defaultValue`): (`result`) => `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<`T` | [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`>> : `T` | [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`> ### Type Parameters #### R `R` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> #### T `T` ### Parameters #### defaultValue `T` ### Returns (`result`) => `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<`T` | [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`>> : `T` | [`InferSuccess`](/byethrow/api/types/Result.InferSuccess.md)\<`R`> --- url: /byethrow/api/functions/Result.unwrapError.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # Function: unwrapError() Extracts the error value from a [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). If the input is a [Success](/byethrow/api/types/Result.Success.md), it will throw the success value or return the default value if provided. - `Failure(e)`: `e` is returned → `e` - `Success(a)`: `a` is thrown if no default value is given → `throw a` - `Success(a)`: the default value `d` is returned → `d` ## Type Param **R** The input [Result](/byethrow/api/types/Result.Result.md) or [ResultAsync](/byethrow/api/types/Result.ResultAsync.md). ## Type Param **T** The default value type (optional). ## Examples **Failure Case (without default)** ```ts import { Result } from '@praha/byethrow'; const result: Result.Result = Result.fail('Oops'); const error = Result.unwrapError(result); // 'Oops' ``` **Failure Case (with default)** ```ts import { Result } from '@praha/byethrow'; const result: Result.Result = Result.fail('Oops'); const error = Result.unwrapError(result, 'default'); // 'Oops' ``` **Success Case (without default)** ```ts import { Result } from '@praha/byethrow'; const result: Result.Result = Result.succeed(100); const error = Result.unwrapError(result); // throws 100 ``` **Success Case (with default)** ```ts import { Result } from '@praha/byethrow'; const result: Result.Result = Result.succeed(100); const error = Result.unwrapError(result, 0); // 0 ``` ## See [assertFailure](/byethrow/api/functions/Result.assertFailure.md) - When used with [assertFailure](/byethrow/api/functions/Result.assertFailure.md), you can safely unwrap the [Result](/byethrow/api/types/Result.Result.md). ## Call Signature > **unwrapError**\<`R`>(`result`): `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<[`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`>> : [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`> ### Type Parameters #### R `R` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> ### Parameters #### result `R` ### Returns `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<[`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`>> : [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`> ## Call Signature > **unwrapError**\<`R`, `T`>(`result`, `defaultValue`): `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<`T` | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`>> : `T` | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`> ### Type Parameters #### R `R` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> #### T `T` ### Parameters #### result `R` #### defaultValue `T` ### Returns `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<`T` | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`>> : `T` | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`> ## Call Signature > **unwrapError**\<`R`>(): (`result`) => `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<[`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`>> : [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`> ### Type Parameters #### R `R` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> ### Returns (`result`) => `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<[`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`>> : [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`> ## Call Signature > **unwrapError**\<`R`, `T`>(`defaultValue`): (`result`) => `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<`T` | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`>> : `T` | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`> ### Type Parameters #### R `R` _extends_ [`ResultMaybeAsync`](/byethrow/api/types/Result.ResultMaybeAsync.md)\<`any`, `any`> #### T `T` ### Parameters #### defaultValue `T` ### Returns (`result`) => `true` _extends_ `HasPromise`\<`R`> ? `Promise`\<`T` | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`>> : `T` | [`InferFailure`](/byethrow/api/types/Result.InferFailure.md)\<`R`> --- url: /byethrow/index.md --- > For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt. # byethrow A lightweight Result type package > Say goodbye to throw, embrace type-safe results [Introduction](./guide/start/introduction) | [Quick Start](./guide/start/quick) ```sh [npm] npm install @praha/byethrow ``` ```sh [pnpm] pnpm add @praha/byethrow ``` ```sh [yarn] yarn add @praha/byethrow ``` ```sh [bun] bun add @praha/byethrow ``` ## Error handling that the compiler understands Every failure becomes a value. No hidden throws, no forgotten catches, no surprises in production. - [**Errors are values**](./guide/tutorial/basics/result-type): Functions return Result instead of throwing. Success carries the value, Failure carries the error, and the type checker makes sure you handle both. - [**Just plain objects**](./guide/best-practices/result-vs-throw): No classes, no instanceof, no hidden state. Log it, serialize it, send it across the wire as it is. - [**Sync and async, one API**](./api/modules/Result): Every function accepts both Result and Promise. There is no second API to learn. - [**Composable by design**](./guide/tutorial/chaining/pipe-basics): Chain steps with pipe. Each function only runs on success, and a failure flows straight through to the end. - [**Ship only what you use**](./guide/best-practices/importing-result): Each function is an independent export, so bundlers drop everything you never call. - [**Batteries included**](./guide/ecosystem/linter): A linter plugin, test matchers and documentation for AI assistants keep the whole team on the same patterns. ## Every failure path, visible in the types ### Wrap code that throws Result.fn turns a throwing or async function into one that returns a Result. ```ts title=fetch-user.ts import { Result } from '@praha/byethrow'; type User = { id: string; name: string }; const fetchUser = Result.fn({ try: async (id: string): Promise => { const response = await fetch(`/api/users/${id}`); if (!response.ok) throw new Error(`HTTP ${response.status}`); return response.json(); }, catch: (error) => new Error('Failed to fetch user', { cause: error }), }); const result = await fetchUser('u_123'); ``` [`Result.fn`](./api/functions/Result.fn) | [Read the guide](./guide/tutorial/basics/wrapping-functions) ### Validate unknown input Result.parse accepts any Standard Schema, such as Zod, Valibot or ArkType. ```ts title=sign-up.ts import { Result } from '@praha/byethrow'; import { z } from 'zod'; const SignUp = z.object({ name: z.string().min(1), email: z.email(), }); const result = Result.parse(SignUp, await request.json()); ``` [`Result.parse`](./api/functions/Result.parse) | [Read the guide](./guide/tutorial/basics/parsing-values) ### Compose steps with pipe Each step runs only on success, and every possible error adds up in the type. ```ts title=welcome.ts import { Result } from '@praha/byethrow'; const result = await Result.pipe( Result.succeed('u_123'), Result.andThen(validateId), Result.andThen(findUser), Result.andThrough(sendWelcomeMail), Result.map((user) => `Welcome, ${user.name}!`), ); if (Result.isFailure(result)) { const { error } = result; } ``` [`Result.pipe`](./api/functions/Result.pipe) | [`Result.andThen`](./api/functions/Result.andThen) | [`Result.andThrough`](./api/functions/Result.andThrough) | [`Result.map`](./api/functions/Result.map) | [Read the guide](./guide/tutorial/chaining/pipe-basics) ### Combine independent results Result.collect waits for all of them and reports every failure, not just the first. ```ts title=dashboard.ts import { Result } from '@praha/byethrow'; // Waits for every request and keeps all failures, not just the first const result = await Result.collect({ user: fetchUser('u_123'), posts: fetchPosts('u_123'), settings: fetchSettings('u_123'), }); if (Result.isFailure(result)) { const errors = result.error; } ``` [`Result.collect`](./api/functions/Result.collect) | [`Result.isFailure`](./api/functions/Result.isFailure) | [Read the guide](./guide/tutorial/combining/aggregating-results) ### Handle every error case Pair it with ts-pattern for exhaustive matching, so a new error type fails to compile. ```ts title=delete-post.ts import { Result } from '@praha/byethrow'; import { match } from 'ts-pattern'; await Result.pipe( deletePost('post_1'), Result.inspect(() => toast.success('Post deleted')), Result.inspectError((error) => match(error) .with({ name: 'PostNotFoundError' }, () => toast.info('Already deleted')) .with({ name: 'PostPermissionError' }, () => toast.error('Not allowed')) // Adding a new error type turns this line into a compile error .exhaustive(), ), ); ``` [`Result.inspect`](./api/functions/Result.inspect) | [`Result.inspectError`](./api/functions/Result.inspectError) | [Read the guide](./guide/best-practices/pattern-matching) ## Say goodbye to throw. Install the package and turn your first function into one that returns a Result. It takes about a minute. [Read the guide](./guide/start/introduction) | [Browse the API](./api/)