#Result を集約する
複数のバリデーションやリクエストの結果など、いくつもの Result があるとき、それらをひとつの Result にまとめたいことがよくあります。
sequence と collect はどちらもこれを行う関数です。Result の配列またはオブジェクトを受け取り、失敗の扱い方が異なります。
#sequence で最初の失敗で停止する
sequence(results)ケースを選ぶと、その流れだけを追えますsequence は、すべての Result が成功した場合、すべての値を含む Success を返します。
そうでない場合は、最初に見つかった失敗を返します。
import { import Result Result } from '@praha/byethrow';
// すべて成功
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).@exampleObject 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 } }
@exampleObject 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' }
@exampleArray 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] }
@exampleArray 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' }
@exampleUsing 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] }
@exampleUsing 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.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith 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.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith 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.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith 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] }
// 最初の失敗を返す
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).@exampleObject 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 } }
@exampleObject 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' }
@exampleArray 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] }
@exampleArray 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' }
@exampleUsing 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] }
@exampleUsing 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.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith 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.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.fail('Something went wrong');
// Result.Result<never, string>
@exampleWith 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.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.fail('Something went wrong');
// Result.Result<never, string>
@exampleWith 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' }オブジェクトを渡した場合、成功値は同じキーを持つオブジェクトになります。
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).@exampleObject 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 } }
@exampleObject 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' }
@exampleArray 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] }
@exampleArray 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' }
@exampleUsing 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] }
@exampleUsing 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.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith 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.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith 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 } }#collect ですべてのエラーを収集する
collect(results)ケースを選ぶと、その流れだけを追えますcollect も、すべての Result が成功した場合は、すべての値を含む Success を返します。
そうでない場合は、すべてのエラーを配列にした Failure を返します。
import { import Result Result } from '@praha/byethrow';
// すべて成功
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).@exampleObject 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 } }
@exampleObject 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'] }
@exampleArray 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] }
@exampleArray 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'] }
@exampleUsing 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] }
@exampleUsing 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.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith 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.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith 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.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith 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] }
// すべての失敗を返す
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).@exampleObject 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 } }
@exampleObject 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'] }
@exampleArray 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] }
@exampleArray 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'] }
@exampleUsing 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] }
@exampleUsing 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.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith 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.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.fail('Something went wrong');
// Result.Result<never, string>
@exampleWith 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.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.fail('Something went wrong');
// Result.Result<never, string>
@exampleWith 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'] }#例:フォームのバリデーション
collect はフォームのバリデーションに最適です。ユーザーには問題を 1 つずつではなく、すべてまとめて見せるべきだからです。
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.@exampleimport { 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.@exampleimport { 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.@exampleimport { 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).@exampleObject 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 } }
@exampleObject 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'] }
@exampleArray 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] }
@exampleArray 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'] }
@exampleUsing 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] }
@exampleUsing 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'] }#マッパー関数を使う
どちらの関数も、プレーンな値の配列と、各値を 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: NumberConstructorAn object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers.
Number .NumberConstructor.isNaN(number: unknown): booleanReturns 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.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.fail('Something went wrong');
// Result.Result<never, string>
@exampleWith 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.@exampleSynchronous Usage
import { Result } from '@praha/byethrow';
const result = Result.succeed(42);
// Result.Result<42, never>
@exampleWith 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).@exampleObject 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 } }
@exampleObject 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' }
@exampleArray 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] }
@exampleArray 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' }
@exampleUsing 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] }
@exampleUsing 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).@exampleObject 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 } }
@exampleObject 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'] }
@exampleArray 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] }
@exampleArray 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'] }
@exampleUsing 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] }
@exampleUsing 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'] }sequence では、マッパー関数は要素ごとに 1 つずつ呼び出され、失敗が起きると残りの要素に対しては呼び出されません。
collect では、マッパー関数はすべての要素に対して呼び出されます。
#非同期での挙動
どちらの関数も ResultAsync を受け取ることができ、入力のいずれかが非同期であれば ResultAsync を返します。
非同期処理がどのように実行されるかは、処理の渡し方によって変わります。
#Result を直接渡す場合
配列やオブジェクトのリテラルの中に fetchUser(id) と書くと、リクエストはその場で、つまり sequence や collect が呼ばれるより前に開始されます。
どちらの関数も、すでに実行中の処理をどう待つかを決めているだけです。
import { import Result Result } from '@praha/byethrow';
// 両方のリクエストがすぐに開始され、並行して実行される
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).@exampleObject 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 } }
@exampleObject 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'] }
@exampleArray 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] }
@exampleArray 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'] }
@exampleUsing 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] }
@exampleUsing 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 ),
});
// 型: Result.Result<{ user: User; orders: Order[] }, FetchError[]>collectはすべての完了を待ち、すべてのエラーを報告します。sequenceは順番に完了を待ち、失敗が見つかった時点で結果を返します。他の処理がキャンセルされるわけではなく、その結果が無視されるだけです。
sequence→Failure(e2)task1task2task3collect→Failure([e2])task1task2task3#マッパー関数を使う場合
マッパー関数を使うと、処理を開始するのは sequence や collect 自身になるため、違いがはっきりと現れます。
import { import Result Result } from '@praha/byethrow';
// collect: すべてのリクエストが一斉に開始され、並列に実行される
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).@exampleObject 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 } }
@exampleObject 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'] }
@exampleArray 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] }
@exampleArray 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'] }
@exampleUsing 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] }
@exampleUsing 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: 各マイグレーションは前のマイグレーションが成功してから開始され、
// 失敗した後の残りのマイグレーションはスキップされる
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).@exampleObject 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 } }
@exampleObject 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' }
@exampleArray 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] }
@exampleArray 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' }
@exampleUsing 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] }
@exampleUsing 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 ,
);sequence→Failure(e2)fn(1)fn(2)fn(3)collect→Failure([e2])fn(1)fn(2)fn(3)#sequence と collect の使い分け
| シナリオ | 推奨 |
|---|---|
| フォームのバリデーションなど、すべてのエラーを一度に報告したい | collect |
| 互いに独立した非同期処理を並列に実行したい | collect |
| 最初のエラーだけが分かればよい | sequence |
| 処理を 1 つずつ実行し、失敗したら残りをスキップしたい | マッパー関数を指定した sequence |
#リファレンス
| API | 用途 |
|---|---|
| sequence(values) | 最初の失敗で停止しながら Result をまとめる |
| collect(values) | すべてのエラーを収集しながら Result をまとめる |
