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/basics/result-type.md.
  • 日本語
  • Result 型について

    関数を使い始める前に、Result 型とは何か、なぜ便利なのかを見ていきましょう。

    Result とは?

    Result は、失敗する可能性のある操作の結果を表します。 常に次の 2 つの状態のどちらかになります。

    • Success:操作が成功し、value を持ちます。
    • Failure:操作が失敗し、error を持ちます。

    例外を投げる方法とは異なり、Result を返すと失敗の可能性が型システムそのものに表現されます。

    構造

    Result は、2 つの状態を区別する type プロパティを持つプレーンオブジェクトです。

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    // Success は値を持つ const
    const success: Result.Success<number>
    success
    :
    import Result
    Result
    .
    type Success<T> = {
        readonly type: "Success";
        readonly value: T;
    }

    Represents a successful result.

    @typeParamT - The type of the successful value.@example
    import { Result } from '@praha/byethrow';
    
    const success: Result.Success<number> = {
      type: 'Success',
      value: 42,
    };
    @categoryCore Types
    Success
    <number> = {
    type: "Success"
    type
    : 'Success',
    value: number
    value
    : 42,
    }; // Failure はエラーを持つ const
    const failure: Result.Failure<string>
    failure
    :
    import Result
    Result
    .
    type Failure<E> = {
        readonly type: "Failure";
        readonly error: E;
    }

    Represents a failed result.

    @typeParamE - The type of the error.@example
    import { Result } from '@praha/byethrow';
    
    const failure: Result.Failure<string> = {
      type: 'Failure',
      error: 'Something went wrong',
    };
    @categoryCore Types
    Failure
    <string> = {
    type: "Failure"
    type
    : 'Failure',
    error: string
    error
    : 'Something went wrong',
    };

    ただのオブジェクトなので、Result はそのままログに出力したり、JSON にシリアライズしたり、テストで比較したりできます。 実際には、このオブジェクトを手で書くことはほとんどありません。次のページでは、これらを作成するヘルパー関数を紹介します。

    ユニオン型

    Result.Result<T, E> は Success<T> と Failure<E> のユニオン型です。 T は成功値の型、E はエラーの型です。

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    // Success<number> または Failure<string> を返す const
    const divide: (a: number, b: number) => Result.Result<number, string>
    divide
    = (
    a: number
    a
    : number,
    b: number
    b
    : number):
    import Result
    Result
    .
    type Result<T, E> = Result.Success<T> | Result.Failure<E>

    A union type representing either a success or a failure.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@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
    <number, string> => {
    if (
    b: number
    b
    === 0) {
    return {
    type: "Failure"
    type
    : 'Failure',
    error: string
    error
    : 'Cannot divide by zero' };
    } return {
    type: "Success"
    type
    : 'Success',
    value: number
    value
    :
    a: number
    a
    /
    b: number
    b
    };
    }; const
    const result: Result.Result<number, string>
    result
    =
    const divide: (a: number, b: number) => Result.Result<number, string>
    divide
    (10, 2);
    // 型: Result.Result<number, string>

    なぜ例外ではなく Result を使うのか?

    1. 失敗がシグネチャに現れる

    例外の場合、関数が例外を投げるかどうかはシグネチャからわかりません。

    // ❌ 例外を投げる?シグネチャからはわからない
    const 
    const parseConfig: (path: string) => Config
    parseConfig
    = (
    path: string
    path
    : string):
    type Config = {
        host: string;
        port: number;
    }
    Config
    => {
    // ... }

    Result を使えば、戻り値の型から明らかになります。

    // ✅ 失敗する可能性とその内容が戻り値の型からわかる
    const 
    const parseConfig: (path: string) => Result.Result<Config, ParseError>
    parseConfig
    = (
    path: string
    path
    : string):
    import Result
    Result
    .
    type Result<T, E> = Result.Success<T> | Result.Failure<E>

    A union type representing either a success or a failure.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@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 Config = {
        host: string;
        port: number;
    }
    Config
    ,
    class ParseError
    ParseError
    > => {
    // ... }

    2. エラーが型を保つ

    catch した例外は常に unknown です。Result はエラーの正確な型を保ちます。

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    type
    type ValidationError = {
        field: string;
        message: string;
    }
    ValidationError
    = {
    field: string
    field
    : string;
    message: string
    message
    : string };
    const
    const validateEmail: (email: string) => Result.Result<string, ValidationError>
    validateEmail
    = (
    email: string
    email
    : string):
    import Result
    Result
    .
    type Result<T, E> = Result.Success<T> | Result.Failure<E>

    A union type representing either a success or a failure.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@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
    <string,
    type ValidationError = {
        field: string;
        message: string;
    }
    ValidationError
    > => {
    if (!
    email: string
    email
    .
    String.includes(searchString: string, position?: number): boolean

    Returns true if searchString appears as a substring of the result of converting this object to a String, at one or more positions that are greater than or equal to position; otherwise, returns false.

    @paramsearchString search string@paramposition If position is undefined, 0 is assumed, so as to search all of the String.
    includes
    ('@')) {
    return
    import Result
    Result
    .
    function fail<{
        readonly field: "email";
        readonly message: "Invalid email format";
    }>(error: {
        readonly field: "email";
        readonly message: "Invalid email format";
    }): Result.Result<never, {
        readonly field: "email";
        readonly message: "Invalid email format";
    }> (+1 overload)

    Creates a Failure result from a given error.

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

    @typeParamE - The type of the error to wrap.@returnsA Result containing the given error.@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
    ({
    field: "email"
    field
    : 'email',
    message: "Invalid email format"
    message
    : 'Invalid email format' });
    } return
    import Result
    Result
    .
    function succeed<string>(value: string): Result.Result<string, never> (+1 overload)

    Creates a Success result from a given value.

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

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@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
    (
    email: string
    email
    );
    }; const
    const result: Result.Result<string, ValidationError>
    result
    =
    const validateEmail: (email: string) => Result.Result<string, ValidationError>
    validateEmail
    ('test');
    if (
    import Result
    Result
    .
    function isFailure<Result.Result<string, ValidationError>>(result: Result.Result<string, ValidationError>): result is Result.Failure<ValidationError>

    Type guard to check if a Result is a Failure .

    @typeParamR - The type of the result to check.@paramresult - The Result to check.@returnstrue if the result is a Failure , otherwise false.@example
    import { Result } from '@praha/byethrow';
    
    const result: Result.Result<number, string> = { type: 'Failure', error: 'Something went wrong' };
    if (Result.isFailure(result)) {
      console.error(result.error); // Safe access to error
    }
    @categoryType Guards
    isFailure
    (
    const result: Result.Result<string, ValidationError>
    result
    )) {
    // TypeScript は result.error が ValidationError であることを知っている
    var console: Console
    console
    .
    Console.log(...data: any[]): void

    The console.log() static method outputs a message to the console.

    MDN Reference

    log
    (`Error in ${
    const result: Result.Failure<ValidationError>
    result
    .
    error: ValidationError
    error
    .
    field: string
    field
    }: ${
    const result: Result.Failure<ValidationError>
    result
    .
    error: ValidationError
    error
    .
    message: string
    message
    }`);
    }

    3. Result は合成できる

    Result はつなげて使うことができ、各ステップのエラー型は自動的にユニオン型として集められます。 その仕組みは「処理をつなげる」章で学びます。

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    const
    const result: Result.ResultAsync<User, ValidationError | TransformError | SaveError>
    result
    =
    import Result
    Result
    .
    function pipe<Result.Result<{
        id: string;
        name: string;
    }, never>, Result.Result<User, ValidationError>, Result.Result<User, ValidationError | TransformError>, Result.ResultAsync<User, ValidationError | TransformError | SaveError>>(a: Result.Result<{
        id: string;
        name: string;
    }, never>, ab: (a: Result.Result<{
        id: string;
        name: string;
    }, never>) => Result.Result<User, ValidationError>, bc: (b: Result.Result<...>) => Result.Result<...>, cd: (c: Result.Result<...>) => Result.ResultAsync<...>): Result.ResultAsync<...> (+25 overloads)

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

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

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@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<{
        id: string;
        name: string;
    }>(value: {
        id: string;
        name: string;
    }): Result.Result<{
        id: string;
        name: string;
    }, never> (+1 overload)

    Creates a Success result from a given value.

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

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@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 input: {
        id: string;
        name: string;
    }
    input
    ),
    import Result
    Result
    .
    function andThen<Result.Result<{
        id: string;
        name: string;
    }, never>, Result.Result<User, ValidationError>>(fn: (a: {
        id: string;
        name: string;
    }) => Result.Result<User, ValidationError>): (result: Result.Result<{
        id: string;
        name: string;
    }, never>) => Result.Result<User, ValidationError> (+1 overload)

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

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@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 validate: (value: User) => Result.Result<User, ValidationError>
    validate
    ),
    import Result
    Result
    .
    function andThen<Result.Result<User, ValidationError>, Result.Result<User, TransformError>>(fn: (a: User) => Result.Result<User, TransformError>): (result: Result.Result<User, ValidationError>) => Result.Result<User, ValidationError | TransformError> (+1 overload)

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

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@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 transform: (value: User) => Result.Result<User, TransformError>
    transform
    ),
    import Result
    Result
    .
    function andThen<Result.Result<User, ValidationError | TransformError>, Result.ResultAsync<User, SaveError>>(fn: (a: User) => Result.ResultAsync<User, SaveError>): (result: Result.Result<User, ValidationError | TransformError>) => Result.ResultAsync<User, ValidationError | TransformError | SaveError> (+1 overload)

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

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@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 save: (value: User) => Result.ResultAsync<User, SaveError>
    save
    ),
    ); // 型: Result.ResultAsync<User, ValidationError | TransformError | SaveError>

    非同期の Result

    非同期の Result は ResultAsync<T, E> で表します。これは単なる Promise<Result<T, E>> のエイリアスです。

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    const
    const asyncResult: Result.ResultAsync<number, never>
    asyncResult
    :
    import Result
    Result
    .
    type ResultAsync<T, E> = Promise<Result.Result<T, E>>

    An asynchronous variant of Result , wrapped in a Promise.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@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
    <number, never> =
    var Promise: PromiseConstructor

    Represents the completion of an asynchronous operation

    Promise
    .
    PromiseConstructor.resolve<Result.Result<42, never>>(value: Result.Result<42, never>): Promise<Result.Result<42, never>> (+2 overloads)

    Creates a new resolved promise for the provided value.

    @paramvalue A promise.@returnsA promise whose internal state matches the provided promise.
    resolve
    (
    import Result
    Result
    .
    function succeed<42>(value: 42): Result.Result<42, never> (+1 overload)

    Creates a Success result from a given value.

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

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@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));
    // 型: Result.ResultAsync<number, never> // ResultAsync はただの Promise なので、await できる const
    const resolved: Result.Result<number, never>
    resolved
    = await
    const asyncResult: Result.ResultAsync<number, never>
    asyncResult
    ;
    // 型: Result.Result<number, never>

    同期と非同期を混在させる

    @praha/byethrow のすべての関数は、Result と ResultAsync の両方を受け付けます。 パイプラインの中で同期と非同期のステップを混在させると、最初の非同期ステップ以降の結果は自動的に ResultAsync になります。

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    // 同期関数 const
    const validate: (input: string) => Result.Result<string, Error>
    validate
    = (
    input: string
    input
    : string):
    import Result
    Result
    .
    type Result<T, E> = Result.Success<T> | Result.Failure<E>

    A union type representing either a success or a failure.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@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
    <string, Error> => {
    if (
    input: string
    input
    .
    String.length: number

    Returns the length of a String object.

    length
    === 0) {
    return
    import Result
    Result
    .
    function fail<Error>(error: Error): Result.Result<never, Error> (+1 overload)

    Creates a Failure result from a given error.

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

    @typeParamE - The type of the error to wrap.@returnsA Result containing the given error.@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
    var Error: ErrorConstructor
    new (message?: string, options?: ErrorOptions) => Error (+1 overload)
    Error
    ('Input is empty'));
    } return
    import Result
    Result
    .
    function succeed<string>(value: string): Result.Result<string, never> (+1 overload)

    Creates a Success result from a given value.

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

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@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
    (
    input: string
    input
    );
    }; // 非同期関数 const
    const fetchData: (input: string) => Result.ResultAsync<number, Error>
    fetchData
    = async (
    input: string
    input
    : string):
    import Result
    Result
    .
    type ResultAsync<T, E> = Promise<Result.Result<T, E>>

    An asynchronous variant of Result , wrapped in a Promise.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@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
    <number, Error> => {
    // API 呼び出しをシミュレート return
    import Result
    Result
    .
    function succeed<number>(value: number): Result.Result<number, never> (+1 overload)

    Creates a Success result from a given value.

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

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@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
    (
    input: string
    input
    .
    String.length: number

    Returns the length of a String object.

    length
    );
    }; const
    const result: Result.ResultAsync<number, Error>
    result
    =
    import Result
    Result
    .
    function pipe<Result.Result<"hello", never>, Result.Result<string, Error>, Result.ResultAsync<number, Error>, Result.ResultAsync<number, Error>>(a: Result.Result<"hello", never>, ab: (a: Result.Result<"hello", never>) => Result.Result<string, Error>, bc: (b: Result.Result<string, Error>) => Result.ResultAsync<number, Error>, cd: (c: Result.ResultAsync<number, Error>) => Result.ResultAsync<number, Error>): Result.ResultAsync<...> (+25 overloads)

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

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

    @typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@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<"hello">(value: "hello"): Result.Result<"hello", never> (+1 overload)

    Creates a Success result from a given value.

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

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@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
    ('hello'),
    import Result
    Result
    .
    function andThen<Result.Result<"hello", never>, Result.Result<string, Error>>(fn: (a: "hello") => Result.Result<string, Error>): (result: Result.Result<"hello", never>) => Result.Result<string, Error> (+1 overload)

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

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@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 validate: (input: string) => Result.Result<string, Error>
    validate
    ), // 同期
    import Result
    Result
    .
    function andThen<Result.Result<string, Error>, Result.ResultAsync<number, Error>>(fn: (a: string) => Result.ResultAsync<number, Error>): (result: Result.Result<string, Error>) => Result.ResultAsync<number, Error> (+1 overload)

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

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@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 fetchData: (input: string) => Result.ResultAsync<number, Error>
    fetchData
    ), // 非同期: ここからパイプラインは非同期になる
    import Result
    Result
    .
    function andThen<Result.ResultAsync<number, Error>, Result.Result<number, never>>(fn: (a: number) => Result.Result<number, never>): (result: Result.ResultAsync<number, Error>) => Result.ResultAsync<number, Error> (+1 overload)

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

    @typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@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
    ((
    n: number
    n
    ) =>
    import Result
    Result
    .
    function succeed<number>(value: number): Result.Result<number, never> (+1 overload)

    Creates a Success result from a given value.

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

    @typeParamT - The type of the value to wrap.@returnsA Result containing the given value.@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
    (
    n: number
    n
    * 2)), // 同期だが、非同期のパイプライン内で実行される
    ); // 型: Result.ResultAsync<number, Error>

    ユーティリティ型

    Result を扱う独自の関数を書くときに役立つ型もいくつか用意されています。

    ResultMaybeAsync

    ResultMaybeAsync<T, E> は、Result<T, E> または ResultAsync<T, E> のどちらかを表します。 実装が同期にも非同期にもなり得る場合に便利です。

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    type
    type User = {
        id: string;
        name: string;
    }
    User
    = {
    id: string
    id
    : string;
    name: string
    name
    : string };
    type
    type UserRepository = {
        findById: (id: string) => Result.ResultMaybeAsync<User, "NotFound">;
    }
    UserRepository
    = {
    // 同期(例: インメモリ)と非同期(例: データベース)のどちらの実装も許容する
    findById: (id: string) => Result.ResultMaybeAsync<User, "NotFound">
    findById
    : (
    id: string
    id
    : string) =>
    import Result
    Result
    .
    type ResultMaybeAsync<T, E> = Result.Result<T, E> | Promise<Result.Result<T, E>>

    A result that may be either synchronous or asynchronous.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@example

    Synchronous Case

    import { Result } from '@praha/byethrow';
    
    const result: Result.ResultMaybeAsync<number, string> = { type: 'Success', value: 10 };
    @example

    Asynchronous Case

    import { Result } from '@praha/byethrow';
    
    const result: Result.ResultMaybeAsync<number, string> = Promise.resolve({ type: 'Failure', error: 'error' });
    @categoryCore Types
    ResultMaybeAsync
    <
    type User = {
        id: string;
        name: string;
    }
    User
    , 'NotFound'>;
    };

    InferSuccess と InferFailure

    InferSuccess と InferFailure は、Result 型、または Result を返す関数から、成功値の型とエラーの型を取り出します。

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

    An asynchronous variant of Result , wrapped in a Promise.

    @typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@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
    <{
    id: string
    id
    : string;
    name: string
    name
    : string }, 'NotFound'>;
    type
    type User = {
        id: string;
        name: string;
    }
    User
    =
    import Result
    Result
    .
    type InferSuccess<T> = [T] extends [(...args: any[]) => Result.ResultMaybeAsync<infer U, any>] ? U : [T] extends [Result.ResultMaybeAsync<infer U, any>] ? U : never

    Infers the Success value type T from a Result or a function returning a Result.

    @typeParamT - A ResultMaybeAsync type or a function returning it.@example

    From a result object

    import { Result } from '@praha/byethrow';
    
    type R = Result.Result<number, string>;
    type SuccessValue = Result.InferSuccess<R>; // number
    @example

    From a function

    import { Result } from '@praha/byethrow';
    
    const fn = () => Promise.resolve({ type: 'Success', value: 123 } as const);
    type SuccessValue = Result.InferSuccess<typeof fn>; // number
    @categoryInfer Types
    InferSuccess
    <typeof
    const findUser: (id: string) => Result.ResultAsync<{
        id: string;
        name: string;
    }, "NotFound">
    findUser
    >;
    // 型: { id: string; name: string } type
    type FindUserError = "NotFound"
    FindUserError
    =
    import Result
    Result
    .
    type InferFailure<T> = [T] extends [(...args: any[]) => Result.ResultMaybeAsync<any, infer U>] ? U : [T] extends [Result.ResultMaybeAsync<any, infer U>] ? U : never

    Infers the Failure value type E from a Result or a function returning a Result.

    @typeParamT - A ResultMaybeAsync type or a function returning it.@example

    From a result object

    import { Result } from '@praha/byethrow';
    
    type R = Result.Result<number, string>;
    type ErrorValue = Result.InferFailure<R>; // string
    @example

    From a function

    import { Result } from '@praha/byethrow';
    
    const fn = () => Promise.resolve({ type: 'Failure', error: new Error() } as const);
    type ErrorValue = Result.InferFailure<typeof fn>; // Error
    @categoryInfer Types
    InferFailure
    <typeof
    const findUser: (id: string) => Result.ResultAsync<{
        id: string;
        name: string;
    }, "NotFound">
    findUser
    >;
    // 型: 'NotFound'

    リファレンス

    API用途
    Success<T>成功した結果を表す
    Failure<E>失敗した結果を表す
    Result<T, E>Success と Failure のユニオン型
    ResultAsync<T, E>Promise<Result<T, E>> のエイリアス
    ResultMaybeAsync<T, E>Result または ResultAsync のどちらか
    ResultFor<R, T, E>R が非同期かどうかに応じて Result か ResultAsync になる
    InferSuccess<T>成功値の型を取り出す
    InferFailure<T>エラーの型を取り出す