For AI agents: the complete documentation index is available at /byethrow/ja/llms.txt, the full documentation bundle is available at /byethrow/ja/llms-full.txt, and this page is available as Markdown at /byethrow/ja/guide/tutorial/chaining/chaining-results.md.
  • 日本語
  • Result をつなげる

    andThen と orElse は、それ自体が Result を返すステップをつなげます。 map と mapError が値を変換するだけなのに対し、これらの関数では各ステップが、パイプラインを成功として続けるか失敗として続けるかを決められます。

    andThen でステップをつなげる

    andThen(fn)ケースを選ぶと、その流れだけを追えます

    andThen は成功値を引数に渡された関数を呼び出し、その関数が返した Result を返します。 入力が Failure の場合、関数は呼び出されず、Failure がそのまま返されます。

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    // 関数が Success を返す const
    const doubled: Result.Result<number, never>
    doubled
    =
    import Result
    Result
    .
    function pipe<Result.Result<3, never>, Result.Result<number, never>>(a: Result.Result<3, never>, ab: (a: Result.Result<3, never>) => Result.Result<number, never>): Result.Result<number, never> (+25 overloads)

    Applies a sequence of functions to a value, from left to right.

    This utility enables function composition in a left-to-right manner. It supports up to 26 chained functions from A through Z.

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
      2,
      x => x + 1,
      x => x * 3,
      x => `Result: ${x}`
    );
    // Result: 9
    @categoryUtilities
    pipe
    (
    import Result
    Result
    .
    function succeed<3>(value: 3): Result.Result<3, never> (+1 overload)

    Creates a Success result from a given value.

    Passing a Promise is allowed, but it is recommended to await it before passing to succeed.

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed(42);
    // Result.Result<42, never>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed();
    // Result.Result<void, never>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    succeed
    (3),
    import Result
    Result
    .
    function andThen<Result.Result<3, never>, Result.Result<number, never>>(fn: (a: 3) => Result.Result<number, never>): (result: Result.Result<3, never>) => Result.Result<number, never> (+1 overload)

    Chains the next computation using the success value of a Result or ResultAsync . If the original result is a Failure , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@example

    Success Case

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // { type: 'Success', value: 6 }
    @example

    Failure Case (input is a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('error'),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // result: { type: 'Failure', error: 'error' }
    @example

    Failure Case (function returns a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.fail('error: ' + x)),
    );
    // result: { type: 'Failure', error: 'error: 3' }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    andThen
    ((
    value: 3
    value
    ) =>
    import Result
    Result
    .
    function succeed<number>(value: number): Result.Result<number, never> (+1 overload)

    Creates a Success result from a given value.

    Passing a Promise is allowed, but it is recommended to await it before passing to succeed.

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed(42);
    // Result.Result<42, never>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed();
    // Result.Result<void, never>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    succeed
    (
    value: 3
    value
    * 2)),
    ); // { type: 'Success', value: 6 } // 関数が Failure を返す const
    const rejected: Result.Result<never, "Rejected: 3">
    rejected
    =
    import Result
    Result
    .
    function pipe<Result.Result<3, never>, Result.Result<never, "Rejected: 3">>(a: Result.Result<3, never>, ab: (a: Result.Result<3, never>) => Result.Result<never, "Rejected: 3">): Result.Result<never, "Rejected: 3"> (+25 overloads)

    Applies a sequence of functions to a value, from left to right.

    This utility enables function composition in a left-to-right manner. It supports up to 26 chained functions from A through Z.

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
      2,
      x => x + 1,
      x => x * 3,
      x => `Result: ${x}`
    );
    // Result: 9
    @categoryUtilities
    pipe
    (
    import Result
    Result
    .
    function succeed<3>(value: 3): Result.Result<3, never> (+1 overload)

    Creates a Success result from a given value.

    Passing a Promise is allowed, but it is recommended to await it before passing to succeed.

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed(42);
    // Result.Result<42, never>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed();
    // Result.Result<void, never>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    succeed
    (3),
    import Result
    Result
    .
    function andThen<Result.Result<3, never>, Result.Result<never, "Rejected: 3">>(fn: (a: 3) => Result.Result<never, "Rejected: 3">): (result: Result.Result<3, never>) => Result.Result<never, "Rejected: 3"> (+1 overload)

    Chains the next computation using the success value of a Result or ResultAsync . If the original result is a Failure , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@example

    Success Case

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // { type: 'Success', value: 6 }
    @example

    Failure Case (input is a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('error'),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // result: { type: 'Failure', error: 'error' }
    @example

    Failure Case (function returns a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.fail('error: ' + x)),
    );
    // result: { type: 'Failure', error: 'error: 3' }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    andThen
    ((
    value: 3
    value
    ) =>
    import Result
    Result
    .
    function fail<"Rejected: 3">(error: "Rejected: 3"): Result.Result<never, "Rejected: 3"> (+1 overload)

    Creates a Failure result from a given error.

    Passing a Promise is allowed, but it is recommended to await it before passing to fail.

    @typeParamE - The type of the error to wrap.@returnsA Result containing the given error.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail('Something went wrong');
    // Result.Result<never, string>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail();
    // Result.Result<never, void>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    fail
    (`Rejected: ${
    value: 3
    value
    }`)),
    ); // { type: 'Failure', error: 'Rejected: 3' } // 入力がすでに Failure const
    const skipped: Result.Result<number, "error">
    skipped
    =
    import Result
    Result
    .
    function pipe<Result.Result<never, "error">, Result.Result<number, "error">>(a: Result.Result<never, "error">, ab: (a: Result.Result<never, "error">) => Result.Result<number, "error">): Result.Result<number, "error"> (+25 overloads)

    Applies a sequence of functions to a value, from left to right.

    This utility enables function composition in a left-to-right manner. It supports up to 26 chained functions from A through Z.

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
      2,
      x => x + 1,
      x => x * 3,
      x => `Result: ${x}`
    );
    // Result: 9
    @categoryUtilities
    pipe
    (
    import Result
    Result
    .
    function fail<"error">(error: "error"): Result.Result<never, "error"> (+1 overload)

    Creates a Failure result from a given error.

    Passing a Promise is allowed, but it is recommended to await it before passing to fail.

    @typeParamE - The type of the error to wrap.@returnsA Result containing the given error.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail('Something went wrong');
    // Result.Result<never, string>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail();
    // Result.Result<never, void>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    fail
    ('error'),
    import Result
    Result
    .
    function andThen<Result.Result<never, "error">, Result.Result<number, never>>(fn: (a: never) => Result.Result<number, never>): (result: Result.Result<never, "error">) => Result.Result<number, "error"> (+1 overload)

    Chains the next computation using the success value of a Result or ResultAsync . If the original result is a Failure , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@example

    Success Case

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // { type: 'Success', value: 6 }
    @example

    Failure Case (input is a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('error'),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // result: { type: 'Failure', error: 'error' }
    @example

    Failure Case (function returns a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.fail('error: ' + x)),
    );
    // result: { type: 'Failure', error: 'error: 3' }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    andThen
    ((
    value: never
    value
    ) =>
    import Result
    Result
    .
    function succeed<number>(value: number): Result.Result<number, never> (+1 overload)

    Creates a Success result from a given value.

    Passing a Promise is allowed, but it is recommended to await it before passing to succeed.

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed(42);
    // Result.Result<42, never>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed();
    // Result.Result<void, never>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    succeed
    (
    value: never
    value
    * 2)), // 呼び出されない
    ); // { type: 'Failure', error: 'error' }

    出力のエラー型は、入力のエラー型と、関数が返すエラー型のユニオンになります。 ステップをつなげていくにつれて、起こりうるすべてのエラーが型として追跡されます。

    例:順番に実行するステップ

    andThen の典型的な使い方は、前のステップの結果を使って次のステップを実行していく一連の処理です。

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    type
    type User = {
        id: string;
        name: string;
        email: string;
    }
    User
    = {
    id: string
    id
    : string;
    name: string
    name
    : string;
    email: string
    email
    : string };
    declare const
    const findUserById: (id: string) => Result.ResultAsync<User, "NotFound">
    findUserById
    : (
    id: string
    id
    : string) =>
    import Result
    Result
    .
    type ResultAsync<T, E> = Promise<Result.Result<T, E>>

    An asynchronous variant of Result , wrapped in a Promise.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@example
    import { Result } from '@praha/byethrow';
    
    const fetchData = async (): Result.ResultAsync<string, Error> => {
      try {
        const data = await fetch('...');
        return { type: 'Success', value: await data.text() };
      } catch (err) {
        return { type: 'Failure', error: err as Error };
      }
    };
    @categoryCore Types
    ResultAsync
    <
    type User = {
        id: string;
        name: string;
        email: string;
    }
    User
    , 'NotFound'>;
    declare const
    const validateEmail: (user: User) => Result.Result<User, "InvalidEmail">
    validateEmail
    : (
    user: User
    user
    :
    type User = {
        id: string;
        name: string;
        email: string;
    }
    User
    ) =>
    import Result
    Result
    .
    type Result<T, E> = Result.Success<T> | Result.Failure<E>

    A union type representing either a success or a failure.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@example
    import { Result } from '@praha/byethrow';
    
    const doSomething = (): Result.Result<number, string> => {
      return Math.random() > 0.5
        ? { type: 'Success', value: 10 }
        : { type: 'Failure', error: 'Oops' };
    };
    @categoryCore Types
    Result
    <
    type User = {
        id: string;
        name: string;
        email: string;
    }
    User
    , 'InvalidEmail'>;
    declare const
    const saveUser: (user: User) => Result.ResultAsync<User, "SaveFailed">
    saveUser
    : (
    user: User
    user
    :
    type User = {
        id: string;
        name: string;
        email: string;
    }
    User
    ) =>
    import Result
    Result
    .
    type ResultAsync<T, E> = Promise<Result.Result<T, E>>

    An asynchronous variant of Result , wrapped in a Promise.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@example
    import { Result } from '@praha/byethrow';
    
    const fetchData = async (): Result.ResultAsync<string, Error> => {
      try {
        const data = await fetch('...');
        return { type: 'Success', value: await data.text() };
      } catch (err) {
        return { type: 'Failure', error: err as Error };
      }
    };
    @categoryCore Types
    ResultAsync
    <
    type User = {
        id: string;
        name: string;
        email: string;
    }
    User
    , 'SaveFailed'>;
    const
    const result: Result.Result<User, "NotFound" | "InvalidEmail" | "SaveFailed">
    result
    = await
    import Result
    Result
    .
    function pipe<Result.Result<"u123", never>, Result.ResultAsync<User, "NotFound">, Result.ResultAsync<User, "NotFound" | "InvalidEmail">, Result.ResultAsync<User, "NotFound" | "InvalidEmail" | "SaveFailed">>(a: Result.Result<"u123", never>, ab: (a: Result.Result<"u123", never>) => Result.ResultAsync<User, "NotFound">, bc: (b: Result.ResultAsync<User, "NotFound">) => Result.ResultAsync<User, "NotFound" | "InvalidEmail">, cd: (c: Result.ResultAsync<...>) => Result.ResultAsync<...>): Result.ResultAsync<...> (+25 overloads)

    Applies a sequence of functions to a value, from left to right.

    This utility enables function composition in a left-to-right manner. It supports up to 26 chained functions from A through Z.

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
      2,
      x => x + 1,
      x => x * 3,
      x => `Result: ${x}`
    );
    // Result: 9
    @categoryUtilities
    pipe
    (
    import Result
    Result
    .
    function succeed<"u123">(value: "u123"): Result.Result<"u123", never> (+1 overload)

    Creates a Success result from a given value.

    Passing a Promise is allowed, but it is recommended to await it before passing to succeed.

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed(42);
    // Result.Result<42, never>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed();
    // Result.Result<void, never>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    succeed
    ('u123'),
    import Result
    Result
    .
    function andThen<Result.Result<"u123", never>, Result.ResultAsync<User, "NotFound">>(fn: (a: "u123") => Result.ResultAsync<User, "NotFound">): (result: Result.Result<"u123", never>) => Result.ResultAsync<User, "NotFound"> (+1 overload)

    Chains the next computation using the success value of a Result or ResultAsync . If the original result is a Failure , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@example

    Success Case

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // { type: 'Success', value: 6 }
    @example

    Failure Case (input is a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('error'),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // result: { type: 'Failure', error: 'error' }
    @example

    Failure Case (function returns a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.fail('error: ' + x)),
    );
    // result: { type: 'Failure', error: 'error: 3' }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    andThen
    (
    const findUserById: (id: string) => Result.ResultAsync<User, "NotFound">
    findUserById
    ),
    import Result
    Result
    .
    function andThen<Result.ResultAsync<User, "NotFound">, Result.Result<User, "InvalidEmail">>(fn: (a: User) => Result.Result<User, "InvalidEmail">): (result: Result.ResultAsync<User, "NotFound">) => Result.ResultAsync<User, "NotFound" | "InvalidEmail"> (+1 overload)

    Chains the next computation using the success value of a Result or ResultAsync . If the original result is a Failure , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@example

    Success Case

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // { type: 'Success', value: 6 }
    @example

    Failure Case (input is a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('error'),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // result: { type: 'Failure', error: 'error' }
    @example

    Failure Case (function returns a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.fail('error: ' + x)),
    );
    // result: { type: 'Failure', error: 'error: 3' }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    andThen
    (
    const validateEmail: (user: User) => Result.Result<User, "InvalidEmail">
    validateEmail
    ),
    import Result
    Result
    .
    function andThen<Result.ResultAsync<User, "NotFound" | "InvalidEmail">, Result.ResultAsync<User, "SaveFailed">>(fn: (a: User) => Result.ResultAsync<User, "SaveFailed">): (result: Result.ResultAsync<User, "NotFound" | "InvalidEmail">) => Result.ResultAsync<User, "NotFound" | "InvalidEmail" | "SaveFailed"> (+1 overload)

    Chains the next computation using the success value of a Result or ResultAsync . If the original result is a Failure , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@example

    Success Case

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // { type: 'Success', value: 6 }
    @example

    Failure Case (input is a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('error'),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // result: { type: 'Failure', error: 'error' }
    @example

    Failure Case (function returns a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.fail('error: ' + x)),
    );
    // result: { type: 'Failure', error: 'error: 3' }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    andThen
    (
    const saveUser: (user: User) => Result.ResultAsync<User, "SaveFailed">
    saveUser
    ),
    ); // 型: Result.Result<User, 'NotFound' | 'InvalidEmail' | 'SaveFailed'> // いずれかのステップが失敗すると、残りのステップはスキップされる
    各ステップの後のエラー型追加削除
    1. Result.succeed('u123'),never
    2. Result.andThen(findUserById),'NotFound'
    3. Result.andThen(validateEmail),'NotFound''InvalidEmail'
    4. Result.andThen(saveUser),'NotFound''InvalidEmail''SaveFailed'

    例:受け入れられない値を拒否する

    andThen は、受け入れられない値を Failure に変える場所でもあります。 たとえば fetch は HTTP のエラーステータスでは例外を投げないため、別のステップでレスポンスを確認します。

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    class
    class NetworkError
    NetworkError
    extends
    var Error: ErrorConstructor
    Error
    {
    override readonly
    NetworkError.name: "NetworkError"
    name
    = 'NetworkError';
    } class
    class HttpError
    HttpError
    extends
    var Error: ErrorConstructor
    Error
    {
    override readonly
    HttpError.name: "HttpError"
    name
    = 'HttpError';
    } const
    const request: (url: string) => Result.ResultAsync<Response, NetworkError>
    request
    =
    import Result
    Result
    .
    function fn<(url: string) => Promise<Response>, NetworkError>(options: {
        try: (url: string) => Promise<Response>;
        catch: (error: unknown) => NetworkError;
    }): (url: string) => Result.ResultAsync<Response, NetworkError> (+3 overloads)

    Wraps a function that may throw and returns a new function that returns a Result or ResultAsync .

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

    @typeParamT - The function type to execute (sync or async) or a Promise type.@typeParamE - The error type to return if catch is used.@returnsA new function that returns a Result or ResultAsync wrapping the original function's return value or the caught error.@example

    Sync try-catch

    import { Result } from '@praha/byethrow';
    
    const fn = Result.fn({
    try: (x: number) => {
    if (x < 0) throw new Error('Negative!');
    return x * 2;
    },
    catch: (error) => new Error('Oops!', { cause: error }),
    });
    
    const result = fn(5); // Result.Result<number, Error>
    @example

    Sync safe

    import { Result } from '@praha/byethrow';
    
    const fn = Result.fn({
    safe: true,
    try: (x: number) => x + 1,
    });
    
    const result = fn(1); // Result.Result<number, never>
    @example

    Async try-catch

    import { Result } from '@praha/byethrow';
    
    const fn = Result.fn({
    try: async (id: string) => await fetch(`/api/data/${id}`),
    catch: (error) => new Error('Oops!', { cause: error }),
    });
    
    const result = await fn('abc'); // Result.ResultAsync<Response, Error>
    @example

    Async safe

    import { Result } from '@praha/byethrow';
    
    const fn = Result.fn({
    safe: true,
    try: async () => await Promise.resolve('ok'),
    });
    
    const result = await fn(); // Result.ResultAsync<string, never>
    @categoryCreators
    fn
    ({
    try: (url: string) => Promise<Response>
    try
    : (
    url: string
    url
    : string) =>
    function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>
    fetch
    (
    url: string
    url
    ),
    catch: (error: unknown) => NetworkError
    catch
    : (
    error: unknown
    error
    ) => new
    constructor NetworkError(message?: string, options?: ErrorOptions): NetworkError (+1 overload)
    NetworkError
    ('Request failed', {
    ErrorOptions.cause?: unknown
    cause
    :
    error: unknown
    error
    }),
    }); const
    const result: Result.Result<Response, NetworkError | HttpError>
    result
    = await
    import Result
    Result
    .
    function pipe<Result.ResultAsync<Response, NetworkError>, Result.ResultAsync<Response, NetworkError | HttpError>>(a: Result.ResultAsync<Response, NetworkError>, ab: (a: Result.ResultAsync<Response, NetworkError>) => Result.ResultAsync<Response, NetworkError | HttpError>): Result.ResultAsync<Response, NetworkError | HttpError> (+25 overloads)

    Applies a sequence of functions to a value, from left to right.

    This utility enables function composition in a left-to-right manner. It supports up to 26 chained functions from A through Z.

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
      2,
      x => x + 1,
      x => x * 3,
      x => `Result: ${x}`
    );
    // Result: 9
    @categoryUtilities
    pipe
    (
    const request: (url: string) => Result.ResultAsync<Response, NetworkError>
    request
    ('/api/users/u123'),
    import Result
    Result
    .
    function andThen<Result.ResultAsync<Response, NetworkError>, Result.Success<Response> | Result.Failure<HttpError>>(fn: (a: Response) => Result.Success<Response> | Result.Failure<HttpError>): (result: Result.ResultAsync<Response, NetworkError>) => Result.ResultAsync<Response, NetworkError | HttpError> (+1 overload)

    Chains the next computation using the success value of a Result or ResultAsync . If the original result is a Failure , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@example

    Success Case

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // { type: 'Success', value: 6 }
    @example

    Failure Case (input is a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('error'),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // result: { type: 'Failure', error: 'error' }
    @example

    Failure Case (function returns a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.fail('error: ' + x)),
    );
    // result: { type: 'Failure', error: 'error: 3' }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    andThen
    ((
    response: Response
    response
    ) => {
    if (!
    response: Response
    response
    .
    Response.ok: boolean

    The ok read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not.

    MDN Reference

    ok
    ) {
    return
    import Result
    Result
    .
    function fail<HttpError>(error: HttpError): Result.Result<never, HttpError> (+1 overload)

    Creates a Failure result from a given error.

    Passing a Promise is allowed, but it is recommended to await it before passing to fail.

    @typeParamE - The type of the error to wrap.@returnsA Result containing the given error.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail('Something went wrong');
    // Result.Result<never, string>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail();
    // Result.Result<never, void>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    fail
    (new
    constructor HttpError(message?: string, options?: ErrorOptions): HttpError (+1 overload)
    HttpError
    (`Unexpected status: ${
    response: Response
    response
    .
    Response.status: number

    The status read-only property of the Response interface contains the HTTP status codes of the response.

    MDN Reference

    status
    }`));
    } return
    import Result
    Result
    .
    function succeed<Response>(value: Response): Result.Result<Response, never> (+1 overload)

    Creates a Success result from a given value.

    Passing a Promise is allowed, but it is recommended to await it before passing to succeed.

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed(42);
    // Result.Result<42, never>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed();
    // Result.Result<void, never>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    succeed
    (
    response: Response
    response
    );
    }), ); // 型: Result.Result<Response, NetworkError | HttpError>

    orElse で回復する

    orElse(fn)ケースを選ぶと、その流れだけを追えます

    orElse は、失敗に対する andThen の対になる関数です。 エラー値を引数に渡された関数を呼び出し、その関数が返した Result を返します。 入力が Success の場合、関数は呼び出されません。

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    // 関数が Success を返して回復する const
    const recovered: Result.Result<"default value", never>
    recovered
    =
    import Result
    Result
    .
    function pipe<Result.Result<never, "original error">, Result.Result<"default value", never>>(a: Result.Result<never, "original error">, ab: (a: Result.Result<never, "original error">) => Result.Result<"default value", never>): Result.Result<"default value", never> (+25 overloads)

    Applies a sequence of functions to a value, from left to right.

    This utility enables function composition in a left-to-right manner. It supports up to 26 chained functions from A through Z.

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
      2,
      x => x + 1,
      x => x * 3,
      x => `Result: ${x}`
    );
    // Result: 9
    @categoryUtilities
    pipe
    (
    import Result
    Result
    .
    function fail<"original error">(error: "original error"): Result.Result<never, "original error"> (+1 overload)

    Creates a Failure result from a given error.

    Passing a Promise is allowed, but it is recommended to await it before passing to fail.

    @typeParamE - The type of the error to wrap.@returnsA Result containing the given error.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail('Something went wrong');
    // Result.Result<never, string>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail();
    // Result.Result<never, void>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    fail
    ('original error'),
    import Result
    Result
    .
    function orElse<Result.Result<never, "original error">, Result.Result<"default value", never>>(fn: (a: "original error") => Result.Result<"default value", never>): (result: Result.Result<never, "original error">) => Result.Result<"default value", never> (+1 overload)

    Chains the next computation using the error value of a Result or ResultAsync . If the original result is a Success , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@example

    Success Case

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(42),
    Result.orElse((error) => Result.succeed(0)),
    );
    // { type: 'Success', value: 42 }
    @example

    Failure Case (function returns a Success)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('original error'),
    Result.orElse((error) => Result.succeed('default value')),
    );
    // result: { type: 'Success', value: 'default value' }
    @example

    Failure Case (function returns a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('original error'),
    Result.orElse((error) => Result.fail('new error: ' + error)),
    );
    // result: { type: 'Failure', error: 'new error: original error' }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    orElse
    (() =>
    import Result
    Result
    .
    function succeed<"default value">(value: "default value"): Result.Result<"default value", never> (+1 overload)

    Creates a Success result from a given value.

    Passing a Promise is allowed, but it is recommended to await it before passing to succeed.

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed(42);
    // Result.Result<42, never>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed();
    // Result.Result<void, never>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    succeed
    ('default value')),
    ); // { type: 'Success', value: 'default value' } // 関数が新しい Failure を返す const
    const replaced: Result.Result<never, "New error: original error">
    replaced
    =
    import Result
    Result
    .
    function pipe<Result.Result<never, "original error">, Result.Result<never, "New error: original error">>(a: Result.Result<never, "original error">, ab: (a: Result.Result<never, "original error">) => Result.Result<never, "New error: original error">): Result.Result<never, "New error: original error"> (+25 overloads)

    Applies a sequence of functions to a value, from left to right.

    This utility enables function composition in a left-to-right manner. It supports up to 26 chained functions from A through Z.

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
      2,
      x => x + 1,
      x => x * 3,
      x => `Result: ${x}`
    );
    // Result: 9
    @categoryUtilities
    pipe
    (
    import Result
    Result
    .
    function fail<"original error">(error: "original error"): Result.Result<never, "original error"> (+1 overload)

    Creates a Failure result from a given error.

    Passing a Promise is allowed, but it is recommended to await it before passing to fail.

    @typeParamE - The type of the error to wrap.@returnsA Result containing the given error.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail('Something went wrong');
    // Result.Result<never, string>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail();
    // Result.Result<never, void>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    fail
    ('original error'),
    import Result
    Result
    .
    function orElse<Result.Result<never, "original error">, Result.Result<never, "New error: original error">>(fn: (a: "original error") => Result.Result<never, "New error: original error">): (result: Result.Result<never, "original error">) => Result.Result<never, "New error: original error"> (+1 overload)

    Chains the next computation using the error value of a Result or ResultAsync . If the original result is a Success , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@example

    Success Case

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(42),
    Result.orElse((error) => Result.succeed(0)),
    );
    // { type: 'Success', value: 42 }
    @example

    Failure Case (function returns a Success)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('original error'),
    Result.orElse((error) => Result.succeed('default value')),
    );
    // result: { type: 'Success', value: 'default value' }
    @example

    Failure Case (function returns a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('original error'),
    Result.orElse((error) => Result.fail('new error: ' + error)),
    );
    // result: { type: 'Failure', error: 'new error: original error' }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    orElse
    ((
    error: "original error"
    error
    ) =>
    import Result
    Result
    .
    function fail<"New error: original error">(error: "New error: original error"): Result.Result<never, "New error: original error"> (+1 overload)

    Creates a Failure result from a given error.

    Passing a Promise is allowed, but it is recommended to await it before passing to fail.

    @typeParamE - The type of the error to wrap.@returnsA Result containing the given error.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail('Something went wrong');
    // Result.Result<never, string>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail();
    // Result.Result<never, void>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    fail
    (`New error: ${
    error: "original error"
    error
    }`)),
    ); // { type: 'Failure', error: 'New error: original error' } // 入力がすでに Success const
    const untouched: Result.Result<0 | 42, never>
    untouched
    =
    import Result
    Result
    .
    function pipe<Result.Result<42, never>, Result.Result<0 | 42, never>>(a: Result.Result<42, never>, ab: (a: Result.Result<42, never>) => Result.Result<0 | 42, never>): Result.Result<0 | 42, never> (+25 overloads)

    Applies a sequence of functions to a value, from left to right.

    This utility enables function composition in a left-to-right manner. It supports up to 26 chained functions from A through Z.

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
      2,
      x => x + 1,
      x => x * 3,
      x => `Result: ${x}`
    );
    // Result: 9
    @categoryUtilities
    pipe
    (
    import Result
    Result
    .
    function succeed<42>(value: 42): Result.Result<42, never> (+1 overload)

    Creates a Success result from a given value.

    Passing a Promise is allowed, but it is recommended to await it before passing to succeed.

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed(42);
    // Result.Result<42, never>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed();
    // Result.Result<void, never>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    succeed
    (42),
    import Result
    Result
    .
    function orElse<Result.Result<42, never>, Result.Result<0, never>>(fn: (a: never) => Result.Result<0, never>): (result: Result.Result<42, never>) => Result.Result<0 | 42, never> (+1 overload)

    Chains the next computation using the error value of a Result or ResultAsync . If the original result is a Success , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@example

    Success Case

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(42),
    Result.orElse((error) => Result.succeed(0)),
    );
    // { type: 'Success', value: 42 }
    @example

    Failure Case (function returns a Success)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('original error'),
    Result.orElse((error) => Result.succeed('default value')),
    );
    // result: { type: 'Success', value: 'default value' }
    @example

    Failure Case (function returns a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('original error'),
    Result.orElse((error) => Result.fail('new error: ' + error)),
    );
    // result: { type: 'Failure', error: 'new error: original error' }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    orElse
    (() =>
    import Result
    Result
    .
    function succeed<0>(value: 0): Result.Result<0, never> (+1 overload)

    Creates a Success result from a given value.

    Passing a Promise is allowed, but it is recommended to await it before passing to succeed.

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed(42);
    // Result.Result<42, never>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed();
    // Result.Result<void, never>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    succeed
    (0)), // 呼び出されない
    ); // { type: 'Success', value: 42 }

    andThen とは異なり、元のエラー型は関数が返すエラー型に置き換えられます。 関数が常に Success を返す場合、エラー型は never になります。

    例:特定のエラーから回復する

    すべてのエラーから回復する必要はありません。 対処できるエラーだけを処理し、それ以外はそのまま返しましょう。

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    type
    type User = {
        id: string;
        name: string;
    }
    User
    = {
    id: string
    id
    : string;
    name: string
    name
    : string };
    declare const
    const findUser: (id: string) => Result.ResultAsync<User, "NotFound" | "Timeout">
    findUser
    : (
    id: string
    id
    : string) =>
    import Result
    Result
    .
    type ResultAsync<T, E> = Promise<Result.Result<T, E>>

    An asynchronous variant of Result , wrapped in a Promise.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@example
    import { Result } from '@praha/byethrow';
    
    const fetchData = async (): Result.ResultAsync<string, Error> => {
      try {
        const data = await fetch('...');
        return { type: 'Success', value: await data.text() };
      } catch (err) {
        return { type: 'Failure', error: err as Error };
      }
    };
    @categoryCore Types
    ResultAsync
    <
    type User = {
        id: string;
        name: string;
    }
    User
    , 'NotFound' | 'Timeout'>;
    const
    const guest: User
    guest
    :
    type User = {
        id: string;
        name: string;
    }
    User
    = {
    id: string
    id
    : 'guest',
    name: string
    name
    : 'Guest' };
    const
    const result: Result.Result<User, "Timeout">
    result
    = await
    import Result
    Result
    .
    function pipe<Result.ResultAsync<User, "NotFound" | "Timeout">, Result.ResultAsync<User, "Timeout">>(a: Result.ResultAsync<User, "NotFound" | "Timeout">, ab: (a: Result.ResultAsync<User, "NotFound" | "Timeout">) => Result.ResultAsync<User, "Timeout">): Result.ResultAsync<User, "Timeout"> (+25 overloads)

    Applies a sequence of functions to a value, from left to right.

    This utility enables function composition in a left-to-right manner. It supports up to 26 chained functions from A through Z.

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
      2,
      x => x + 1,
      x => x * 3,
      x => `Result: ${x}`
    );
    // Result: 9
    @categoryUtilities
    pipe
    (
    const findUser: (id: string) => Result.ResultAsync<User, "NotFound" | "Timeout">
    findUser
    ('u123'),
    import Result
    Result
    .
    function orElse<Result.ResultAsync<User, "NotFound" | "Timeout">, Result.Success<User> | Result.Failure<"Timeout">>(fn: (a: "NotFound" | "Timeout") => Result.Success<User> | Result.Failure<"Timeout">): (result: Result.ResultAsync<User, "NotFound" | "Timeout">) => Result.ResultAsync<User, "Timeout"> (+1 overload)

    Chains the next computation using the error value of a Result or ResultAsync . If the original result is a Success , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@example

    Success Case

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(42),
    Result.orElse((error) => Result.succeed(0)),
    );
    // { type: 'Success', value: 42 }
    @example

    Failure Case (function returns a Success)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('original error'),
    Result.orElse((error) => Result.succeed('default value')),
    );
    // result: { type: 'Success', value: 'default value' }
    @example

    Failure Case (function returns a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('original error'),
    Result.orElse((error) => Result.fail('new error: ' + error)),
    );
    // result: { type: 'Failure', error: 'new error: original error' }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    orElse
    ((
    error: "NotFound" | "Timeout"
    error
    ) => {
    if (
    error: "NotFound" | "Timeout"
    error
    === 'NotFound') {
    return
    import Result
    Result
    .
    function succeed<User>(value: User): Result.Result<User, never> (+1 overload)

    Creates a Success result from a given value.

    Passing a Promise is allowed, but it is recommended to await it before passing to succeed.

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed(42);
    // Result.Result<42, never>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.succeed();
    // Result.Result<void, never>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    succeed
    (
    const guest: User
    guest
    );
    } return
    import Result
    Result
    .
    function fail<"Timeout">(error: "Timeout"): Result.Result<never, "Timeout"> (+1 overload)

    Creates a Failure result from a given error.

    Passing a Promise is allowed, but it is recommended to await it before passing to fail.

    @typeParamE - The type of the error to wrap.@returnsA Result containing the given error.@example

    Synchronous Usage

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail('Something went wrong');
    // Result.Result<never, string>
    @example

    With No Value

    import { Result } from '@praha/byethrow';
    
    const result = Result.fail();
    // Result.Result<never, void>
    @seecollect - For collect multiple Results into a single Result.@seesequence - For sequence multiple Results into a single Result.@categoryCreators
    fail
    (
    error: "Timeout"
    error
    );
    }), ); // 型: Result.Result<User, 'Timeout'>

    'NotFound' はもう起こりえないため、エラー型から消えていることに注目してください。

    各ステップの後のエラー型追加削除
    1. findUser('u123'),'NotFound''Timeout'
    2. Result.orElse((error) => { ... }),'NotFound''Timeout'

    例:フォールバック先を用意する

    orElse は、最初の試みが失敗したときに代替手段を試す場合にも便利です。

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    type
    type Config = {
        apiUrl: string;
        timeout: number;
    }
    Config
    = {
    apiUrl: string
    apiUrl
    : string;
    timeout: number
    timeout
    : number };
    declare const
    const loadConfigFromFile: () => Result.ResultAsync<Config, "FileNotFound">
    loadConfigFromFile
    : () =>
    import Result
    Result
    .
    type ResultAsync<T, E> = Promise<Result.Result<T, E>>

    An asynchronous variant of Result , wrapped in a Promise.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@example
    import { Result } from '@praha/byethrow';
    
    const fetchData = async (): Result.ResultAsync<string, Error> => {
      try {
        const data = await fetch('...');
        return { type: 'Success', value: await data.text() };
      } catch (err) {
        return { type: 'Failure', error: err as Error };
      }
    };
    @categoryCore Types
    ResultAsync
    <
    type Config = {
        apiUrl: string;
        timeout: number;
    }
    Config
    , 'FileNotFound'>;
    declare const
    const loadConfigFromEnv: () => Result.ResultAsync<Config, "EnvNotSet">
    loadConfigFromEnv
    : () =>
    import Result
    Result
    .
    type ResultAsync<T, E> = Promise<Result.Result<T, E>>

    An asynchronous variant of Result , wrapped in a Promise.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@example
    import { Result } from '@praha/byethrow';
    
    const fetchData = async (): Result.ResultAsync<string, Error> => {
      try {
        const data = await fetch('...');
        return { type: 'Success', value: await data.text() };
      } catch (err) {
        return { type: 'Failure', error: err as Error };
      }
    };
    @categoryCore Types
    ResultAsync
    <
    type Config = {
        apiUrl: string;
        timeout: number;
    }
    Config
    , 'EnvNotSet'>;
    const
    const config: Result.Result<Config, "EnvNotSet">
    config
    = await
    import Result
    Result
    .
    function pipe<Result.ResultAsync<Config, "FileNotFound">, Result.ResultAsync<Config, "EnvNotSet">>(a: Result.ResultAsync<Config, "FileNotFound">, ab: (a: Result.ResultAsync<Config, "FileNotFound">) => Result.ResultAsync<Config, "EnvNotSet">): Result.ResultAsync<Config, "EnvNotSet"> (+25 overloads)

    Applies a sequence of functions to a value, from left to right.

    This utility enables function composition in a left-to-right manner. It supports up to 26 chained functions from A through Z.

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
      2,
      x => x + 1,
      x => x * 3,
      x => `Result: ${x}`
    );
    // Result: 9
    @categoryUtilities
    pipe
    (
    const loadConfigFromFile: () => Result.ResultAsync<Config, "FileNotFound">
    loadConfigFromFile
    (),
    import Result
    Result
    .
    function orElse<Result.ResultAsync<Config, "FileNotFound">, Result.ResultAsync<Config, "EnvNotSet">>(fn: (a: "FileNotFound") => Result.ResultAsync<Config, "EnvNotSet">): (result: Result.ResultAsync<Config, "FileNotFound">) => Result.ResultAsync<Config, "EnvNotSet"> (+1 overload)

    Chains the next computation using the error value of a Result or ResultAsync . If the original result is a Success , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@example

    Success Case

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(42),
    Result.orElse((error) => Result.succeed(0)),
    );
    // { type: 'Success', value: 42 }
    @example

    Failure Case (function returns a Success)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('original error'),
    Result.orElse((error) => Result.succeed('default value')),
    );
    // result: { type: 'Success', value: 'default value' }
    @example

    Failure Case (function returns a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('original error'),
    Result.orElse((error) => Result.fail('new error: ' + error)),
    );
    // result: { type: 'Failure', error: 'new error: original error' }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    orElse
    (() =>
    const loadConfigFromEnv: () => Result.ResultAsync<Config, "EnvNotSet">
    loadConfigFromEnv
    ()),
    ); // 型: Result.Result<Config, 'EnvNotSet'> // まずファイルを試し、だめなら環境変数にフォールバックする

    andThen と orElse を組み合わせる

    2 つの関数を組み合わせると、ステップの連結と回復の両方を含むフローを表現できます。

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    type
    type User = {
        id: string;
        name: string;
    }
    User
    = {
    id: string
    id
    : string;
    name: string
    name
    : string };
    declare const
    const fetchUserFromCache: (id: string) => Result.ResultAsync<User, "CacheMiss">
    fetchUserFromCache
    : (
    id: string
    id
    : string) =>
    import Result
    Result
    .
    type ResultAsync<T, E> = Promise<Result.Result<T, E>>

    An asynchronous variant of Result , wrapped in a Promise.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@example
    import { Result } from '@praha/byethrow';
    
    const fetchData = async (): Result.ResultAsync<string, Error> => {
      try {
        const data = await fetch('...');
        return { type: 'Success', value: await data.text() };
      } catch (err) {
        return { type: 'Failure', error: err as Error };
      }
    };
    @categoryCore Types
    ResultAsync
    <
    type User = {
        id: string;
        name: string;
    }
    User
    , 'CacheMiss'>;
    declare const
    const fetchUserFromDb: (id: string) => Result.ResultAsync<User, "NotFound">
    fetchUserFromDb
    : (
    id: string
    id
    : string) =>
    import Result
    Result
    .
    type ResultAsync<T, E> = Promise<Result.Result<T, E>>

    An asynchronous variant of Result , wrapped in a Promise.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@example
    import { Result } from '@praha/byethrow';
    
    const fetchData = async (): Result.ResultAsync<string, Error> => {
      try {
        const data = await fetch('...');
        return { type: 'Success', value: await data.text() };
      } catch (err) {
        return { type: 'Failure', error: err as Error };
      }
    };
    @categoryCore Types
    ResultAsync
    <
    type User = {
        id: string;
        name: string;
    }
    User
    , 'NotFound'>;
    declare const
    const validateUser: (user: User) => Result.Result<User, "Invalid">
    validateUser
    : (
    user: User
    user
    :
    type User = {
        id: string;
        name: string;
    }
    User
    ) =>
    import Result
    Result
    .
    type Result<T, E> = Result.Success<T> | Result.Failure<E>

    A union type representing either a success or a failure.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@example
    import { Result } from '@praha/byethrow';
    
    const doSomething = (): Result.Result<number, string> => {
      return Math.random() > 0.5
        ? { type: 'Success', value: 10 }
        : { type: 'Failure', error: 'Oops' };
    };
    @categoryCore Types
    Result
    <
    type User = {
        id: string;
        name: string;
    }
    User
    , 'Invalid'>;
    const
    const getValidatedUser: (id: string) => Result.ResultAsync<User, "NotFound" | "Invalid">
    getValidatedUser
    = (
    id: string
    id
    : string) =>
    import Result
    Result
    .
    function pipe<Result.ResultAsync<User, "CacheMiss">, Result.ResultAsync<User, "NotFound">, Result.ResultAsync<User, "NotFound" | "Invalid">>(a: Result.ResultAsync<User, "CacheMiss">, ab: (a: Result.ResultAsync<User, "CacheMiss">) => Result.ResultAsync<User, "NotFound">, bc: (b: Result.ResultAsync<User, "NotFound">) => Result.ResultAsync<User, "NotFound" | "Invalid">): Result.ResultAsync<User, "NotFound" | "Invalid"> (+25 overloads)

    Applies a sequence of functions to a value, from left to right.

    This utility enables function composition in a left-to-right manner. It supports up to 26 chained functions from A through Z.

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@example
    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
      2,
      x => x + 1,
      x => x * 3,
      x => `Result: ${x}`
    );
    // Result: 9
    @categoryUtilities
    pipe
    (
    const fetchUserFromCache: (id: string) => Result.ResultAsync<User, "CacheMiss">
    fetchUserFromCache
    (
    id: string
    id
    ),
    import Result
    Result
    .
    function orElse<Result.ResultAsync<User, "CacheMiss">, Result.ResultAsync<User, "NotFound">>(fn: (a: "CacheMiss") => Result.ResultAsync<User, "NotFound">): (result: Result.ResultAsync<User, "CacheMiss">) => Result.ResultAsync<User, "NotFound"> (+1 overload)

    Chains the next computation using the error value of a Result or ResultAsync . If the original result is a Success , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@example

    Success Case

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(42),
    Result.orElse((error) => Result.succeed(0)),
    );
    // { type: 'Success', value: 42 }
    @example

    Failure Case (function returns a Success)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('original error'),
    Result.orElse((error) => Result.succeed('default value')),
    );
    // result: { type: 'Success', value: 'default value' }
    @example

    Failure Case (function returns a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('original error'),
    Result.orElse((error) => Result.fail('new error: ' + error)),
    );
    // result: { type: 'Failure', error: 'new error: original error' }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    orElse
    (() =>
    const fetchUserFromDb: (id: string) => Result.ResultAsync<User, "NotFound">
    fetchUserFromDb
    (
    id: string
    id
    )),
    import Result
    Result
    .
    function andThen<Result.ResultAsync<User, "NotFound">, Result.Result<User, "Invalid">>(fn: (a: User) => Result.Result<User, "Invalid">): (result: Result.ResultAsync<User, "NotFound">) => Result.ResultAsync<User, "NotFound" | "Invalid"> (+1 overload)

    Chains the next computation using the success value of a Result or ResultAsync . If the original result is a Failure , it is returned unchanged. Otherwise, the provided function is called, and its result is returned as-is.

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@example

    Success Case

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // { type: 'Success', value: 6 }
    @example

    Failure Case (input is a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.fail('error'),
    Result.andThen((x) => Result.succeed(x * 2)),
    );
    // result: { type: 'Failure', error: 'error' }
    @example

    Failure Case (function returns a Failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.pipe(
    Result.succeed(3),
    Result.andThen((x) => Result.fail('error: ' + x)),
    );
    // result: { type: 'Failure', error: 'error: 3' }
    @seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators
    andThen
    (
    const validateUser: (user: User) => Result.Result<User, "Invalid">
    validateUser
    ),
    ); // まずキャッシュを試し、だめならデータベースにフォールバックし、最後にユーザーを検証する
    SuccessFailureステップの結果を切り替えると、Result の行き先が変わります
    fetchUserFromCache(id),
    Result.orElse(() => fetchUserFromDb(id)),
    Result.andThen(validateUser),
    結果Success

    リファレンス

    API用途
    andThen(fn)成功値を使って次のステップをつなげる
    orElse(fn)エラー値を使って失敗から回復する