For AI agents: the complete documentation index is available at /byethrow/llms.txt, the full documentation bundle is available at /byethrow/llms-full.txt, and this page is available as Markdown at /byethrow/guide/tutorial/combining/aggregating-results.md.
  • English
  • Aggregating Results

    When you have several Results, such as the outcomes of multiple validations or requests, you often want to combine them into a single Result. sequence and collect both do this. They accept an array or an object of Results, and differ in how they handle failures.

    Stopping at the First Failure with sequence

    sequence(results)Select a case to follow its path

    sequence returns a Success containing all values if every Result succeeds. Otherwise, it returns the first failure it encounters:

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    // All succeed const
    const success: Result.Result<[1, 2, 3], never>
    success
    =
    import Result
    Result
    .
    function sequence<[Result.Result<1, never>, Result.Result<2, never>, Result.Result<3, never>]>(x: [Result.Result<1, never>, Result.Result<2, never>, Result.Result<3, never>]): Result.Result<[1, 2, 3], never> (+4 overloads)

    Processes multiple Result or ResultAsync values into a single result. If all results are Success , returns a Success containing all values. If any result is a Failure , immediately stops processing and returns a Failure with that single error.

    Unlike collect , which processes all results and collects all errors, sequence stops at the first error and returns only that error.

    @typeParamX - The input type (object or array of Results).@example

    Object of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence({
    name: Result.succeed('Alice'),
    age: Result.succeed(20),
    });
    // { type: 'Success', value: { name: 'Alice', age: 20 } }
    @example

    Object of Results (stops at first failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence({
    name: Result.succeed('Alice'),
    age: Result.fail('Invalid age'),
    });
    // { type: 'Failure', error: 'Invalid age' }
    @example

    Array of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence([
    Result.succeed(1),
    Result.succeed(2),
    ]);
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Array of Results (stops at first failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence([
    Result.succeed(1),
    Result.fail('error1'),
    ]);
    // { type: 'Failure', error: 'error1' }
    @example

    Using a mapper function (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence(['1', '2', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Using a mapper function (stops at first failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence(['1', 'invalid', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Failure', error: 'Invalid number: invalid' }
    @categoryUtilities
    sequence
    ([
    import Result
    Result
    .
    function succeed<1>(value: 1): Result.Result<1, 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
    (1),
    import Result
    Result
    .
    function succeed<2>(value: 2): Result.Result<2, 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
    (2),
    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),
    ]); // { type: 'Success', value: [1, 2, 3] } // Returns the first failure const
    const failure: Result.Result<[1, never, never], "error1" | "error2">
    failure
    =
    import Result
    Result
    .
    function sequence<[Result.Result<1, never>, Result.Result<never, "error1">, Result.Result<never, "error2">]>(x: [Result.Result<1, never>, Result.Result<never, "error1">, Result.Result<never, "error2">]): Result.Result<[1, never, never], "error1" | "error2"> (+4 overloads)

    Processes multiple Result or ResultAsync values into a single result. If all results are Success , returns a Success containing all values. If any result is a Failure , immediately stops processing and returns a Failure with that single error.

    Unlike collect , which processes all results and collects all errors, sequence stops at the first error and returns only that error.

    @typeParamX - The input type (object or array of Results).@example

    Object of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence({
    name: Result.succeed('Alice'),
    age: Result.succeed(20),
    });
    // { type: 'Success', value: { name: 'Alice', age: 20 } }
    @example

    Object of Results (stops at first failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence({
    name: Result.succeed('Alice'),
    age: Result.fail('Invalid age'),
    });
    // { type: 'Failure', error: 'Invalid age' }
    @example

    Array of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence([
    Result.succeed(1),
    Result.succeed(2),
    ]);
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Array of Results (stops at first failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence([
    Result.succeed(1),
    Result.fail('error1'),
    ]);
    // { type: 'Failure', error: 'error1' }
    @example

    Using a mapper function (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence(['1', '2', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Using a mapper function (stops at first failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence(['1', 'invalid', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Failure', error: 'Invalid number: invalid' }
    @categoryUtilities
    sequence
    ([
    import Result
    Result
    .
    function succeed<1>(value: 1): Result.Result<1, 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
    (1),
    import Result
    Result
    .
    function fail<"error1">(error: "error1"): Result.Result<never, "error1"> (+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
    ('error1'),
    import Result
    Result
    .
    function fail<"error2">(error: "error2"): Result.Result<never, "error2"> (+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
    ('error2'),
    ]); // { type: 'Failure', error: 'error1' }

    When given an object, the success value is an object with the same keys:

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    const
    const result: Result.Result<{
        name: "Alice";
        age: 30;
    }, never>
    result
    =
    import Result
    Result
    .
    function sequence<{
        name: Result.Result<"Alice", never>;
        age: Result.Result<30, never>;
    }>(x: {
        name: Result.Result<"Alice", never>;
        age: Result.Result<30, never>;
    }): Result.Result<{
        name: "Alice";
        age: 30;
    }, never> (+4 overloads)

    Processes multiple Result or ResultAsync values into a single result. If all results are Success , returns a Success containing all values. If any result is a Failure , immediately stops processing and returns a Failure with that single error.

    Unlike collect , which processes all results and collects all errors, sequence stops at the first error and returns only that error.

    @typeParamX - The input type (object or array of Results).@example

    Object of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence({
    name: Result.succeed('Alice'),
    age: Result.succeed(20),
    });
    // { type: 'Success', value: { name: 'Alice', age: 20 } }
    @example

    Object of Results (stops at first failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence({
    name: Result.succeed('Alice'),
    age: Result.fail('Invalid age'),
    });
    // { type: 'Failure', error: 'Invalid age' }
    @example

    Array of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence([
    Result.succeed(1),
    Result.succeed(2),
    ]);
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Array of Results (stops at first failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence([
    Result.succeed(1),
    Result.fail('error1'),
    ]);
    // { type: 'Failure', error: 'error1' }
    @example

    Using a mapper function (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence(['1', '2', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Using a mapper function (stops at first failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence(['1', 'invalid', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Failure', error: 'Invalid number: invalid' }
    @categoryUtilities
    sequence
    ({
    name: Result.Result<"Alice", never>
    name
    :
    import Result
    Result
    .
    function succeed<"Alice">(value: "Alice"): Result.Result<"Alice", 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
    ('Alice'),
    age: Result.Result<30, never>
    age
    :
    import Result
    Result
    .
    function succeed<30>(value: 30): Result.Result<30, 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
    (30),
    }); // { type: 'Success', value: { name: 'Alice', age: 30 } }

    Collecting Every Error with collect

    collect(results)Select a case to follow its path

    collect also returns a Success containing all values if every Result succeeds. Otherwise, it returns a Failure containing an array of all errors:

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    // All succeed const
    const success: Result.Result<[1, 2, 3], never[]>
    success
    =
    import Result
    Result
    .
    function collect<[Result.Result<1, never>, Result.Result<2, never>, Result.Result<3, never>]>(x: [Result.Result<1, never>, Result.Result<2, never>, Result.Result<3, never>]): Result.Result<[1, 2, 3], never[]> (+4 overloads)

    Processes multiple Result or ResultAsync values into a single result. If all results are Success , returns a Success containing all values. If any result is a Failure , returns a Failure containing an array of all errors.

    Unlike sequence , which stops at the first error and returns only that error, collect processes all results and collects all errors.

    @typeParamX - The input type (object or array of Results).@example

    Object of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect({
    name: Result.succeed('Alice'),
    age: Result.succeed(20),
    });
    // { type: 'Success', value: { name: 'Alice', age: 20 } }
    @example

    Object of Results (some fail)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect({
    name: Result.succeed('Alice'),
    age: Result.fail('Invalid age'),
    });
    // { type: 'Failure', error: ['Invalid age'] }
    @example

    Array of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect([
    Result.succeed(1),
    Result.succeed(2),
    Result.succeed(3),
    ]);
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Array of Results (some fail)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect([
    Result.succeed(1),
    Result.fail('error1'),
    Result.fail('error2'),
    ]);
    // { type: 'Failure', error: ['error1', 'error2'] }
    @example

    Using a mapper function (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect(['1', '2', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Using a mapper function (some fail)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect(['1', 'invalid', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Failure', error: ['Invalid number: invalid'] }
    @categoryUtilities
    collect
    ([
    import Result
    Result
    .
    function succeed<1>(value: 1): Result.Result<1, 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
    (1),
    import Result
    Result
    .
    function succeed<2>(value: 2): Result.Result<2, 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
    (2),
    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),
    ]); // { type: 'Success', value: [1, 2, 3] } // Returns every failure const
    const failure: Result.Result<[1, never, never], ("error1" | "error2")[]>
    failure
    =
    import Result
    Result
    .
    function collect<[Result.Result<1, never>, Result.Result<never, "error1">, Result.Result<never, "error2">]>(x: [Result.Result<1, never>, Result.Result<never, "error1">, Result.Result<never, "error2">]): Result.Result<[1, never, never], ("error1" | "error2")[]> (+4 overloads)

    Processes multiple Result or ResultAsync values into a single result. If all results are Success , returns a Success containing all values. If any result is a Failure , returns a Failure containing an array of all errors.

    Unlike sequence , which stops at the first error and returns only that error, collect processes all results and collects all errors.

    @typeParamX - The input type (object or array of Results).@example

    Object of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect({
    name: Result.succeed('Alice'),
    age: Result.succeed(20),
    });
    // { type: 'Success', value: { name: 'Alice', age: 20 } }
    @example

    Object of Results (some fail)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect({
    name: Result.succeed('Alice'),
    age: Result.fail('Invalid age'),
    });
    // { type: 'Failure', error: ['Invalid age'] }
    @example

    Array of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect([
    Result.succeed(1),
    Result.succeed(2),
    Result.succeed(3),
    ]);
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Array of Results (some fail)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect([
    Result.succeed(1),
    Result.fail('error1'),
    Result.fail('error2'),
    ]);
    // { type: 'Failure', error: ['error1', 'error2'] }
    @example

    Using a mapper function (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect(['1', '2', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Using a mapper function (some fail)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect(['1', 'invalid', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Failure', error: ['Invalid number: invalid'] }
    @categoryUtilities
    collect
    ([
    import Result
    Result
    .
    function succeed<1>(value: 1): Result.Result<1, 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
    (1),
    import Result
    Result
    .
    function fail<"error1">(error: "error1"): Result.Result<never, "error1"> (+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
    ('error1'),
    import Result
    Result
    .
    function fail<"error2">(error: "error2"): Result.Result<never, "error2"> (+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
    ('error2'),
    ]); // { type: 'Failure', error: ['error1', 'error2'] }

    Example: Form Validation

    collect is ideal for validating a form, where the user should see every problem at once rather than one at a time:

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    type
    type SignUpInput = {
        name: string;
        email: string;
        password: string;
    }
    SignUpInput
    = {
    name: string
    name
    : string;
    email: string
    email
    : string;
    password: string
    password
    : string };
    declare const
    const validateName: (name: string) => Result.Result<string, "NameRequired">
    validateName
    : (
    name: string
    name
    : 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, 'NameRequired'>;
    declare const
    const validateEmail: (email: string) => Result.Result<string, "InvalidEmail">
    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, 'InvalidEmail'>;
    declare const
    const validatePassword: (password: string) => Result.Result<string, "PasswordTooShort">
    validatePassword
    : (
    password: string
    password
    : 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, 'PasswordTooShort'>;
    const
    const validateSignUp: (input: SignUpInput) => Result.Result<{
        name: string;
        email: string;
        password: string;
    }, ("NameRequired" | "InvalidEmail" | "PasswordTooShort")[]>
    validateSignUp
    = (
    input: SignUpInput
    input
    :
    type SignUpInput = {
        name: string;
        email: string;
        password: string;
    }
    SignUpInput
    ) =>
    import Result
    Result
    .
    function collect<{
        name: Result.Result<string, "NameRequired">;
        email: Result.Result<string, "InvalidEmail">;
        password: Result.Result<string, "PasswordTooShort">;
    }>(x: {
        name: Result.Result<string, "NameRequired">;
        email: Result.Result<string, "InvalidEmail">;
        password: Result.Result<string, "PasswordTooShort">;
    }): Result.Result<{
        name: string;
        email: string;
        password: string;
    }, ("NameRequired" | "InvalidEmail" | "PasswordTooShort")[]> (+4 overloads)

    Processes multiple Result or ResultAsync values into a single result. If all results are Success , returns a Success containing all values. If any result is a Failure , returns a Failure containing an array of all errors.

    Unlike sequence , which stops at the first error and returns only that error, collect processes all results and collects all errors.

    @typeParamX - The input type (object or array of Results).@example

    Object of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect({
    name: Result.succeed('Alice'),
    age: Result.succeed(20),
    });
    // { type: 'Success', value: { name: 'Alice', age: 20 } }
    @example

    Object of Results (some fail)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect({
    name: Result.succeed('Alice'),
    age: Result.fail('Invalid age'),
    });
    // { type: 'Failure', error: ['Invalid age'] }
    @example

    Array of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect([
    Result.succeed(1),
    Result.succeed(2),
    Result.succeed(3),
    ]);
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Array of Results (some fail)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect([
    Result.succeed(1),
    Result.fail('error1'),
    Result.fail('error2'),
    ]);
    // { type: 'Failure', error: ['error1', 'error2'] }
    @example

    Using a mapper function (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect(['1', '2', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Using a mapper function (some fail)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect(['1', 'invalid', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Failure', error: ['Invalid number: invalid'] }
    @categoryUtilities
    collect
    ({
    name: Result.Result<string, "NameRequired">
    name
    :
    const validateName: (name: string) => Result.Result<string, "NameRequired">
    validateName
    (
    input: SignUpInput
    input
    .
    name: string
    name
    ),
    email: Result.Result<string, "InvalidEmail">
    email
    :
    const validateEmail: (email: string) => Result.Result<string, "InvalidEmail">
    validateEmail
    (
    input: SignUpInput
    input
    .
    email: string
    email
    ),
    password: Result.Result<string, "PasswordTooShort">
    password
    :
    const validatePassword: (password: string) => Result.Result<string, "PasswordTooShort">
    validatePassword
    (
    input: SignUpInput
    input
    .
    password: string
    password
    ),
    });
    const validateSignUp: (input: SignUpInput) => Result.Result<{
        name: string;
        email: string;
        password: string;
    }, ("NameRequired" | "InvalidEmail" | "PasswordTooShort")[]>
    validateSignUp
    ({
    name: string
    name
    : '',
    email: string
    email
    : 'invalid',
    password: string
    password
    : 'correct horse battery staple' });
    // { type: 'Failure', error: ['NameRequired', 'InvalidEmail'] }

    Using a Mapper Function

    Both functions also accept an array of plain values and a mapper function that converts each value into a Result:

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    const
    const parseNumber: (input: string) => Result.Failure<`Invalid number: ${string}`> | Result.Success<number>
    parseNumber
    = (
    input: string
    input
    : string) => {
    const
    const number: number
    number
    =
    var Number: NumberConstructor
    (value?: any) => number

    An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers.

    Number
    (
    input: string
    input
    );
    if (
    var Number: NumberConstructor

    An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers.

    Number
    .
    NumberConstructor.isNaN(number: unknown): boolean

    Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter to a number. Only values of the type number, that are also NaN, result in true.

    @paramnumber A numeric value.
    isNaN
    (
    const number: number
    number
    )) {
    return
    import Result
    Result
    .
    function fail<`Invalid number: ${string}`>(error: `Invalid number: ${string}`): Result.Result<never, `Invalid number: ${string}`> (+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
    (`Invalid number: ${
    input: string
    input
    }`);
    } 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
    (
    const number: number
    number
    );
    };
    import Result
    Result
    .
    function sequence<["1", "abc", "xyz"], (input: string) => Result.Failure<`Invalid number: ${string}`> | Result.Success<number>>(x: ["1", "abc", "xyz"], fn: (input: string) => Result.Failure<`Invalid number: ${string}`> | Result.Success<number>): Result.Result<[number, number, number], `Invalid number: ${string}`> (+4 overloads)

    Processes multiple Result or ResultAsync values into a single result. If all results are Success , returns a Success containing all values. If any result is a Failure , immediately stops processing and returns a Failure with that single error.

    Unlike collect , which processes all results and collects all errors, sequence stops at the first error and returns only that error.

    @typeParamX - The input type (object or array of Results).@example

    Object of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence({
    name: Result.succeed('Alice'),
    age: Result.succeed(20),
    });
    // { type: 'Success', value: { name: 'Alice', age: 20 } }
    @example

    Object of Results (stops at first failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence({
    name: Result.succeed('Alice'),
    age: Result.fail('Invalid age'),
    });
    // { type: 'Failure', error: 'Invalid age' }
    @example

    Array of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence([
    Result.succeed(1),
    Result.succeed(2),
    ]);
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Array of Results (stops at first failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence([
    Result.succeed(1),
    Result.fail('error1'),
    ]);
    // { type: 'Failure', error: 'error1' }
    @example

    Using a mapper function (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence(['1', '2', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Using a mapper function (stops at first failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence(['1', 'invalid', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Failure', error: 'Invalid number: invalid' }
    @categoryUtilities
    sequence
    (['1', 'abc', 'xyz'],
    const parseNumber: (input: string) => Result.Failure<`Invalid number: ${string}`> | Result.Success<number>
    parseNumber
    );
    // { type: 'Failure', error: 'Invalid number: abc' }
    import Result
    Result
    .
    function collect<["1", "abc", "xyz"], (input: string) => Result.Failure<`Invalid number: ${string}`> | Result.Success<number>>(x: ["1", "abc", "xyz"], fn: (input: string) => Result.Failure<`Invalid number: ${string}`> | Result.Success<number>): Result.Result<[number, number, number], `Invalid number: ${string}`[]> (+4 overloads)

    Processes multiple Result or ResultAsync values into a single result. If all results are Success , returns a Success containing all values. If any result is a Failure , returns a Failure containing an array of all errors.

    Unlike sequence , which stops at the first error and returns only that error, collect processes all results and collects all errors.

    @typeParamX - The input type (object or array of Results).@example

    Object of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect({
    name: Result.succeed('Alice'),
    age: Result.succeed(20),
    });
    // { type: 'Success', value: { name: 'Alice', age: 20 } }
    @example

    Object of Results (some fail)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect({
    name: Result.succeed('Alice'),
    age: Result.fail('Invalid age'),
    });
    // { type: 'Failure', error: ['Invalid age'] }
    @example

    Array of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect([
    Result.succeed(1),
    Result.succeed(2),
    Result.succeed(3),
    ]);
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Array of Results (some fail)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect([
    Result.succeed(1),
    Result.fail('error1'),
    Result.fail('error2'),
    ]);
    // { type: 'Failure', error: ['error1', 'error2'] }
    @example

    Using a mapper function (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect(['1', '2', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Using a mapper function (some fail)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect(['1', 'invalid', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Failure', error: ['Invalid number: invalid'] }
    @categoryUtilities
    collect
    (['1', 'abc', 'xyz'],
    const parseNumber: (input: string) => Result.Failure<`Invalid number: ${string}`> | Result.Success<number>
    parseNumber
    );
    // { type: 'Failure', error: ['Invalid number: abc', 'Invalid number: xyz'] }

    With sequence, the mapper is called for one element at a time and is not called for the remaining elements once a failure occurs. With collect, the mapper is called for every element.

    Async Behavior

    Both functions accept ResultAsync values and return a ResultAsync if any input is asynchronous. How the async operations run depends on how you pass them.

    Passing Results Directly

    When you write fetchUser(id) inside an array or object literal, the request starts right there, before sequence or collect is even called. Both functions only decide how to wait for operations that are already running:

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    // Both requests start immediately and run concurrently const
    const result: Result.Result<{
        user: User;
        orders: Order[];
    }, FetchError[]>
    result
    = await
    import Result
    Result
    .
    function collect<{
        user: Result.ResultAsync<User, FetchError>;
        orders: Result.ResultAsync<Order[], FetchError>;
    }>(x: {
        user: Result.ResultAsync<User, FetchError>;
        orders: Result.ResultAsync<Order[], FetchError>;
    }): Result.ResultAsync<{
        user: User;
        orders: Order[];
    }, FetchError[]> (+4 overloads)

    Processes multiple Result or ResultAsync values into a single result. If all results are Success , returns a Success containing all values. If any result is a Failure , returns a Failure containing an array of all errors.

    Unlike sequence , which stops at the first error and returns only that error, collect processes all results and collects all errors.

    @typeParamX - The input type (object or array of Results).@example

    Object of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect({
    name: Result.succeed('Alice'),
    age: Result.succeed(20),
    });
    // { type: 'Success', value: { name: 'Alice', age: 20 } }
    @example

    Object of Results (some fail)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect({
    name: Result.succeed('Alice'),
    age: Result.fail('Invalid age'),
    });
    // { type: 'Failure', error: ['Invalid age'] }
    @example

    Array of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect([
    Result.succeed(1),
    Result.succeed(2),
    Result.succeed(3),
    ]);
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Array of Results (some fail)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect([
    Result.succeed(1),
    Result.fail('error1'),
    Result.fail('error2'),
    ]);
    // { type: 'Failure', error: ['error1', 'error2'] }
    @example

    Using a mapper function (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect(['1', '2', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Using a mapper function (some fail)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect(['1', 'invalid', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Failure', error: ['Invalid number: invalid'] }
    @categoryUtilities
    collect
    ({
    user: Result.ResultAsync<User, FetchError>
    user
    :
    const fetchUser: (id: string) => Result.ResultAsync<User, FetchError>
    fetchUser
    (
    const userId: string
    userId
    ),
    orders: Result.ResultAsync<Order[], FetchError>
    orders
    :
    const fetchOrders: (userId: string) => Result.ResultAsync<Order[], FetchError>
    fetchOrders
    (
    const userId: string
    userId
    ),
    }); // Type: Result.Result<{ user: User; orders: Order[] }, FetchError[]>
    • collect waits for all of them and reports every error.
    • sequence waits for them in order and returns as soon as it finds a failure. The other operations are not cancelled; their results are simply ignored.
    Failing operation
    sequenceFailure(e2)
    task1
    task2
    task3
    result ignored
    collectFailure([e2])
    task1
    task2
    task3

    Using a Mapper Function

    With a mapper function, the operations are started by sequence or collect itself, so the difference becomes significant:

    import { 
    import Result
    Result
    } from '@praha/byethrow';
    // collect: all requests start at once and run in parallel const
    const users: Result.Result<[User, User, User], FetchError[]>
    users
    = await
    import Result
    Result
    .
    function collect<["u1", "u2", "u3"], (id: string) => Result.ResultAsync<User, FetchError>>(x: ["u1", "u2", "u3"], fn: (id: string) => Result.ResultAsync<User, FetchError>): Result.ResultAsync<[User, User, User], FetchError[]> (+4 overloads)

    Processes multiple Result or ResultAsync values into a single result. If all results are Success , returns a Success containing all values. If any result is a Failure , returns a Failure containing an array of all errors.

    Unlike sequence , which stops at the first error and returns only that error, collect processes all results and collects all errors.

    @typeParamX - The input type (object or array of Results).@example

    Object of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect({
    name: Result.succeed('Alice'),
    age: Result.succeed(20),
    });
    // { type: 'Success', value: { name: 'Alice', age: 20 } }
    @example

    Object of Results (some fail)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect({
    name: Result.succeed('Alice'),
    age: Result.fail('Invalid age'),
    });
    // { type: 'Failure', error: ['Invalid age'] }
    @example

    Array of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect([
    Result.succeed(1),
    Result.succeed(2),
    Result.succeed(3),
    ]);
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Array of Results (some fail)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect([
    Result.succeed(1),
    Result.fail('error1'),
    Result.fail('error2'),
    ]);
    // { type: 'Failure', error: ['error1', 'error2'] }
    @example

    Using a mapper function (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect(['1', '2', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Using a mapper function (some fail)

    import { Result } from '@praha/byethrow';
    
    const result = Result.collect(['1', 'invalid', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Failure', error: ['Invalid number: invalid'] }
    @categoryUtilities
    collect
    (['u1', 'u2', 'u3'],
    const fetchUser: (id: string) => Result.ResultAsync<User, FetchError>
    fetchUser
    );
    // sequence: each migration starts only after the previous one succeeded, // and the remaining migrations are skipped after a failure const
    const migrations: Result.Result<[void, void, void], "MigrationFailed">
    migrations
    = await
    import Result
    Result
    .
    function sequence<["001-create-users", "002-add-email", "003-create-posts"], (name: string) => Result.ResultAsync<void, "MigrationFailed">>(x: ["001-create-users", "002-add-email", "003-create-posts"], fn: (name: string) => Result.ResultAsync<void, "MigrationFailed">): Result.ResultAsync<[void, void, void], "MigrationFailed"> (+4 overloads)

    Processes multiple Result or ResultAsync values into a single result. If all results are Success , returns a Success containing all values. If any result is a Failure , immediately stops processing and returns a Failure with that single error.

    Unlike collect , which processes all results and collects all errors, sequence stops at the first error and returns only that error.

    @typeParamX - The input type (object or array of Results).@example

    Object of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence({
    name: Result.succeed('Alice'),
    age: Result.succeed(20),
    });
    // { type: 'Success', value: { name: 'Alice', age: 20 } }
    @example

    Object of Results (stops at first failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence({
    name: Result.succeed('Alice'),
    age: Result.fail('Invalid age'),
    });
    // { type: 'Failure', error: 'Invalid age' }
    @example

    Array of Results (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence([
    Result.succeed(1),
    Result.succeed(2),
    ]);
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Array of Results (stops at first failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence([
    Result.succeed(1),
    Result.fail('error1'),
    ]);
    // { type: 'Failure', error: 'error1' }
    @example

    Using a mapper function (all succeed)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence(['1', '2', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Success', value: [1, 2, 3] }
    @example

    Using a mapper function (stops at first failure)

    import { Result } from '@praha/byethrow';
    
    const result = Result.sequence(['1', 'invalid', '3'], (value) => {
    const number = Number(value);
    return Number.isNaN(number)
    ? Result.fail(`Invalid number: ${value}`)
    : Result.succeed(number);
    });
    // { type: 'Failure', error: 'Invalid number: invalid' }
    @categoryUtilities
    sequence
    (
    ['001-create-users', '002-add-email', '003-create-posts'],
    const runMigration: (name: string) => Result.ResultAsync<void, "MigrationFailed">
    runMigration
    ,
    );
    Failing operation
    sequenceFailure(e2)
    fn(1)
    fn(2)
    fn(3)
    not started
    collectFailure([e2])
    fn(1)
    fn(2)
    fn(3)
    Tip

    If later operations must not start after a failure, don't create them up front. Use sequence with a mapper function, or chain the steps with andThen or bind.

    Choosing Between sequence and collect

    ScenarioRecommended
    Report every error at once, such as for form validationcollect
    Run independent async operations in parallelcollect
    Only the first error matterssequence
    Run operations one by one and skip the rest after a failuresequence with a mapper

    References

    APIPurpose
    sequence(values)Combine Results, stopping at the first failure
    collect(values)Combine Results, gathering every error