#オブジェクトを構築する
それぞれ失敗しうる処理から得られる複数の値が必要で、しかも後のステップが前のステップの結果に依存していることがあります。
do / bind / let パターンを使うと、こうした値を 1 フィールドずつひとつのオブジェクトにまとめられます。
#do から始める
do は空のオブジェクトを持つ Success を作成します。これがこのパターンの出発点です。
import { import Result Result } from '@praha/byethrow';
const const start: Result.Result<{}, never> start = import Result Result .function do(): Result.Result<{}, never>
export do
Alias for succeed({}). Commonly used as a neutral base value in functional chains or monadic pipelines.
@exampleimport { Result } from '@praha/byethrow';
const result = Result.do();
// Result.Result<{}, never>
@categoryCreators do ();
// { type: 'Success', value: {} }#bind でフィールドを追加する
bind(name, fn)ケースを選ぶと、その流れだけを追えますbind(name, fn) は、蓄積されたオブジェクトにフィールドを追加します。
- それまでに蓄積されたオブジェクトを引数に
fnを呼び出します。 fnがSuccessを返した場合、その値をnameというキーでオブジェクトに追加します。fnがFailureを返した場合、パイプラインはそこで停止し、そのFailureが返されます。
import { import Result Result } from '@praha/byethrow';
const const result: Result.Result<{
name: "Alice";
age: 30;
}, never>
result = import Result Result .function pipe<Result.Result<{}, never>, Result.Result<{
name: "Alice";
}, never>, Result.Result<{
name: "Alice";
age: 30;
}, never>>(a: Result.Result<{}, never>, ab: (a: Result.Result<{}, never>) => Result.Result<{
name: "Alice";
}, never>, bc: (b: Result.Result<{
name: "Alice";
}, never>) => Result.Result<{
name: "Alice";
age: 30;
}, never>): Result.Result<{
name: "Alice";
age: 30;
}, never> (+25 overloads)
Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
import Result Result .function do(): Result.Result<{}, never>
export do
Alias for succeed({}). Commonly used as a neutral base value in functional chains or monadic pipelines.
@exampleimport { Result } from '@praha/byethrow';
const result = Result.do();
// Result.Result<{}, never>
@categoryCreators do (),
import Result Result .function bind<"name", Result.Result<{}, never>, Result.Result<"Alice", never>>(name: "name", fn: (a: {}) => Result.Result<"Alice", never>): (result: Result.Result<{}, never>) => Result.Result<{
name: "Alice";
}, never> (+1 overload)
Chains another
Result
-producing computation and merges its success value
into the existing object under the specified key.
- If the original result is a
Failure
, it is returned as-is.
- If the next result is a
Failure
, it is returned as-is.
- If both are
Success
, a new object is returned by shallow-merging:
the original success object and { [name]: nextSuccess }.
This is useful for building up objects in a compositional and type-safe way,
especially in validation or data-fetching pipelines.
@typeParamN - The key to assign the result of the fn computation.@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Success', value: { name: 1, age: 20 } }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.fail('error')),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators bind ('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')),
import Result Result .function bind<"age", Result.Result<{
name: "Alice";
}, never>, Result.Result<30, never>>(name: "age", fn: (a: {
name: "Alice";
}) => Result.Result<30, never>): (result: Result.Result<{
name: "Alice";
}, never>) => Result.Result<{
name: "Alice";
age: 30;
}, never> (+1 overload)
Chains another
Result
-producing computation and merges its success value
into the existing object under the specified key.
- If the original result is a
Failure
, it is returned as-is.
- If the next result is a
Failure
, it is returned as-is.
- If both are
Success
, a new object is returned by shallow-merging:
the original success object and { [name]: nextSuccess }.
This is useful for building up objects in a compositional and type-safe way,
especially in validation or data-fetching pipelines.
@typeParamN - The key to assign the result of the fn computation.@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Success', value: { name: 1, age: 20 } }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.fail('error')),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators bind ('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 } }#前の値を利用する
bind の重要な特徴は、各ステップがそれより前に追加されたフィールドを利用できることです。
import { import Result Result } from '@praha/byethrow';
const const result: Result.Result<{
user: {
id: string;
profileId: string;
};
profile: {
bio: string;
};
}, "UserNotFound" | "ProfileNotFound">
result = await import Result Result .function pipe<Result.Result<{}, never>, Result.ResultAsync<{
user: {
id: string;
profileId: string;
};
}, "UserNotFound">, Result.ResultAsync<{
user: {
id: string;
profileId: string;
};
profile: {
bio: string;
};
}, "UserNotFound" | "ProfileNotFound">>(a: Result.Result<{}, never>, ab: (a: Result.Result<{}, never>) => Result.ResultAsync<{
user: {
id: string;
profileId: string;
};
}, "UserNotFound">, bc: (b: Result.ResultAsync<{
user: {
id: string;
profileId: string;
};
}, "UserNotFound">) => Result.ResultAsync<{
user: {
id: string;
profileId: string;
};
profile: {
bio: string;
};
}, "UserNotFound" | "ProfileNotFound">): Result.ResultAsync<...> (+25 overloads)
Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
import Result Result .function do(): Result.Result<{}, never>
export do
Alias for succeed({}). Commonly used as a neutral base value in functional chains or monadic pipelines.
@exampleimport { Result } from '@praha/byethrow';
const result = Result.do();
// Result.Result<{}, never>
@categoryCreators do (),
import Result Result .function bind<"user", Result.Result<{}, never>, Result.ResultAsync<{
id: string;
profileId: string;
}, "UserNotFound">>(name: "user", fn: (a: {}) => Result.ResultAsync<{
id: string;
profileId: string;
}, "UserNotFound">): (result: Result.Result<{}, never>) => Result.ResultAsync<{
user: {
id: string;
profileId: string;
};
}, "UserNotFound"> (+1 overload)
Chains another
Result
-producing computation and merges its success value
into the existing object under the specified key.
- If the original result is a
Failure
, it is returned as-is.
- If the next result is a
Failure
, it is returned as-is.
- If both are
Success
, a new object is returned by shallow-merging:
the original success object and { [name]: nextSuccess }.
This is useful for building up objects in a compositional and type-safe way,
especially in validation or data-fetching pipelines.
@typeParamN - The key to assign the result of the fn computation.@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Success', value: { name: 1, age: 20 } }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.fail('error')),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators bind ('user', () => const fetchUser: (userId: string) => Result.ResultAsync<{
id: string;
profileId: string;
}, "UserNotFound">
fetchUser ('u123')),
import Result Result .function bind<"profile", Result.ResultAsync<{
user: {
id: string;
profileId: string;
};
}, "UserNotFound">, Result.ResultAsync<{
bio: string;
}, "ProfileNotFound">>(name: "profile", fn: (a: {
user: {
id: string;
profileId: string;
};
}) => Result.ResultAsync<{
bio: string;
}, "ProfileNotFound">): (result: Result.ResultAsync<{
user: {
id: string;
profileId: string;
};
}, "UserNotFound">) => Result.ResultAsync<{
user: {
id: string;
profileId: string;
};
profile: {
bio: string;
};
}, "UserNotFound" | "ProfileNotFound"> (+1 overload)
Chains another
Result
-producing computation and merges its success value
into the existing object under the specified key.
- If the original result is a
Failure
, it is returned as-is.
- If the next result is a
Failure
, it is returned as-is.
- If both are
Success
, a new object is returned by shallow-merging:
the original success object and { [name]: nextSuccess }.
This is useful for building up objects in a compositional and type-safe way,
especially in validation or data-fetching pipelines.
@typeParamN - The key to assign the result of the fn computation.@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Success', value: { name: 1, age: 20 } }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.fail('error')),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators bind ('profile', ({ user: {
id: string;
profileId: string;
}
user }) => const fetchProfile: (profileId: string) => Result.ResultAsync<{
bio: string;
}, "ProfileNotFound">
fetchProfile (user: {
id: string;
profileId: string;
}
user .profileId: string profileId )), // `user` を利用
);
// 型: Result.Result<{ user: { id: string; profileId: string }; profile: { bio: string } }, 'UserNotFound' | 'ProfileNotFound'>#失敗すると短絡する
いずれかの bind が失敗すると、残りのステップはスキップされます。
import { import Result Result } from '@praha/byethrow';
const const result: Result.Result<{
a: 1;
b: never;
c: 3;
}, "Error!">
result = import Result Result .function pipe<Result.Result<{}, never>, Result.Result<{
a: 1;
}, never>, Result.Result<{
a: 1;
b: never;
}, "Error!">, Result.Result<{
a: 1;
b: never;
c: 3;
}, "Error!">>(a: Result.Result<{}, never>, ab: (a: Result.Result<{}, never>) => Result.Result<{
a: 1;
}, never>, bc: (b: Result.Result<{
a: 1;
}, never>) => Result.Result<{
a: 1;
b: never;
}, "Error!">, cd: (c: Result.Result<{
a: 1;
b: never;
}, "Error!">) => Result.Result<{
a: 1;
b: never;
c: 3;
}, "Error!">): Result.Result<{
a: 1;
b: never;
c: 3;
}, "Error!"> (+25 overloads)
Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
import Result Result .function do(): Result.Result<{}, never>
export do
Alias for succeed({}). Commonly used as a neutral base value in functional chains or monadic pipelines.
@exampleimport { Result } from '@praha/byethrow';
const result = Result.do();
// Result.Result<{}, never>
@categoryCreators do (),
import Result Result .function bind<"a", Result.Result<{}, never>, Result.Result<1, never>>(name: "a", fn: (a: {}) => Result.Result<1, never>): (result: Result.Result<{}, never>) => Result.Result<{
a: 1;
}, never> (+1 overload)
Chains another
Result
-producing computation and merges its success value
into the existing object under the specified key.
- If the original result is a
Failure
, it is returned as-is.
- If the next result is a
Failure
, it is returned as-is.
- If both are
Success
, a new object is returned by shallow-merging:
the original success object and { [name]: nextSuccess }.
This is useful for building up objects in a compositional and type-safe way,
especially in validation or data-fetching pipelines.
@typeParamN - The key to assign the result of the fn computation.@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Success', value: { name: 1, age: 20 } }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.fail('error')),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators bind ('a', () => 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 bind<"b", Result.Result<{
a: 1;
}, never>, Result.Result<never, "Error!">>(name: "b", fn: (a: {
a: 1;
}) => Result.Result<never, "Error!">): (result: Result.Result<{
a: 1;
}, never>) => Result.Result<{
a: 1;
b: never;
}, "Error!"> (+1 overload)
Chains another
Result
-producing computation and merges its success value
into the existing object under the specified key.
- If the original result is a
Failure
, it is returned as-is.
- If the next result is a
Failure
, it is returned as-is.
- If both are
Success
, a new object is returned by shallow-merging:
the original success object and { [name]: nextSuccess }.
This is useful for building up objects in a compositional and type-safe way,
especially in validation or data-fetching pipelines.
@typeParamN - The key to assign the result of the fn computation.@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Success', value: { name: 1, age: 20 } }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.fail('error')),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators bind ('b', () => import Result Result .function fail<"Error!">(error: "Error!"): Result.Result<never, "Error!"> (+1 overload)Creates a
Failure
result from a given error.
Passing a Promise is allowed, but it is recommended to await it before passing to fail.
@typeParamE - The type of the error to wrap.@returnsA Result containing the given error.@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 ('Error!')), // ここで失敗
import Result Result .function bind<"c", Result.Result<{
a: 1;
b: never;
}, "Error!">, Result.Result<3, never>>(name: "c", fn: (a: {
a: 1;
b: never;
}) => Result.Result<3, never>): (result: Result.Result<{
a: 1;
b: never;
}, "Error!">) => Result.Result<{
a: 1;
b: never;
c: 3;
}, "Error!"> (+1 overload)
Chains another
Result
-producing computation and merges its success value
into the existing object under the specified key.
- If the original result is a
Failure
, it is returned as-is.
- If the next result is a
Failure
, it is returned as-is.
- If both are
Success
, a new object is returned by shallow-merging:
the original success object and { [name]: nextSuccess }.
This is useful for building up objects in a compositional and type-safe way,
especially in validation or data-fetching pipelines.
@typeParamN - The key to assign the result of the fn computation.@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Success', value: { name: 1, age: 20 } }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.fail('error')),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators bind ('c', () => 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: 'Failure', error: 'Error!' }#let で通常の値を追加する
let(name, fn)ケースを選ぶと、その流れだけを追えますフィールドの中には、それまでに追加されたフィールドから計算でき、失敗することのないものもあります。
let(name, fn) は fn が返した値をそのまま追加するため、succeed で包む必要がありません。
import { import Result Result } from '@praha/byethrow';
const const result: Result.Result<{
price: 1000;
quantity: 3;
total: number;
}, never>
result = import Result Result .function pipe<Result.Result<{}, never>, Result.Result<{
price: 1000;
}, never>, Result.Result<{
price: 1000;
quantity: 3;
}, never>, Result.Result<{
price: 1000;
quantity: 3;
total: number;
}, never>>(a: Result.Result<{}, never>, ab: (a: Result.Result<{}, never>) => Result.Result<{
price: 1000;
}, never>, bc: (b: Result.Result<{
price: 1000;
}, never>) => Result.Result<{
price: 1000;
quantity: 3;
}, never>, cd: (c: Result.Result<{
price: 1000;
quantity: 3;
}, never>) => Result.Result<{
price: 1000;
quantity: 3;
total: number;
}, never>): Result.Result<...> (+25 overloads)
Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
import Result Result .function do(): Result.Result<{}, never>
export do
Alias for succeed({}). Commonly used as a neutral base value in functional chains or monadic pipelines.
@exampleimport { Result } from '@praha/byethrow';
const result = Result.do();
// Result.Result<{}, never>
@categoryCreators do (),
import Result Result .function bind<"price", Result.Result<{}, never>, Result.Result<1000, never>>(name: "price", fn: (a: {}) => Result.Result<1000, never>): (result: Result.Result<{}, never>) => Result.Result<{
price: 1000;
}, never> (+1 overload)
Chains another
Result
-producing computation and merges its success value
into the existing object under the specified key.
- If the original result is a
Failure
, it is returned as-is.
- If the next result is a
Failure
, it is returned as-is.
- If both are
Success
, a new object is returned by shallow-merging:
the original success object and { [name]: nextSuccess }.
This is useful for building up objects in a compositional and type-safe way,
especially in validation or data-fetching pipelines.
@typeParamN - The key to assign the result of the fn computation.@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Success', value: { name: 1, age: 20 } }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.fail('error')),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators bind ('price', () => import Result Result .function succeed<1000>(value: 1000): Result.Result<1000, 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 (1000)),
import Result Result .function bind<"quantity", Result.Result<{
price: 1000;
}, never>, Result.Result<3, never>>(name: "quantity", fn: (a: {
price: 1000;
}) => Result.Result<3, never>): (result: Result.Result<{
price: 1000;
}, never>) => Result.Result<{
price: 1000;
quantity: 3;
}, never> (+1 overload)
Chains another
Result
-producing computation and merges its success value
into the existing object under the specified key.
- If the original result is a
Failure
, it is returned as-is.
- If the next result is a
Failure
, it is returned as-is.
- If both are
Success
, a new object is returned by shallow-merging:
the original success object and { [name]: nextSuccess }.
This is useful for building up objects in a compositional and type-safe way,
especially in validation or data-fetching pipelines.
@typeParamN - The key to assign the result of the fn computation.@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Success', value: { name: 1, age: 20 } }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.fail('error')),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators bind ('quantity', () => 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)),
import Result Result .let<"total", Result.Result<{
price: 1000;
quantity: 3;
}, never>, number>(name: "total", fn: (a: {
price: 1000;
quantity: 3;
}) => number): (result: Result.Result<{
price: 1000;
quantity: 3;
}, never>) => Result.Result<{
price: 1000;
quantity: 3;
total: number;
}, never> (+1 overload)
export let
Computes a plain value from the current success object and attaches it
to the existing object under the specified key.
- If the original result is a
Failure
, it is returned as-is.
- If the original result is a
Success
, a new object is returned by shallow-merging:
the original success object and { [name]: fn(value) }.
This is the companion of
bind
for derivations that cannot fail.
fn is expected to be a pure, synchronous computation.
Use
bind
instead when the value comes from a fallible or asynchronous computation.
@typeParamN - The key to assign the result of the fn computation.@typeParamR1 - The input Result or ResultAsync .@typeParamT2 - The value type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ firstName: 'Alice', lastName: 'Smith' }),
Result.let('fullName', ({ firstName, lastName }) => `${firstName} ${lastName}`),
);
// { type: 'Success', value: { firstName: 'Alice', lastName: 'Smith', fullName: 'Alice Smith' } }
@exampleFailure Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.let('fullName', ({ firstName, lastName }) => `${firstName} ${lastName}`),
);
// { type: 'Failure', error: 'error' }
@exampleCombined with bind
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.do(),
Result.bind('x', () => Result.succeed(1)),
Result.bind('y', () => Result.succeed(2)),
Result.let('z', ({ x, y }) => x + y),
);
// { type: 'Success', value: { x: 1, y: 2, z: 3 } }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@seebind - Use this function instead when the value is computed by a Result -producing function.@categoryCombinators let ('total', ({ price: 1000 price , quantity: 3 quantity }) => price: 1000 price * quantity: 3 quantity ),
);
// { type: 'Success', value: { price: 1000, quantity: 3, total: 3000 } }これは Result.bind('total', ({ price, quantity }) => Result.succeed(price * quantity)) と同じですが、そのステップが失敗しないことがひと目でわかります。
let は Promise を自動で await せず、失敗を表現する手段も持ちません。
値が非同期処理や失敗しうる処理から得られる場合は、Result または ResultAsync を返す関数とともに bind を使ってください。
#例:関連データを取得する
あるデータを取得するために別のデータが必要な場合でも、bind を使えば途中の値をすべて最後まで利用できます。
import { import Result Result } from '@praha/byethrow';
type type OrderDetails = {
orderId: string;
customerName: string;
products: {
id: string;
name: string;
price: number;
}[];
totalPrice: number;
}
OrderDetails = {
orderId: string orderId : string;
customerName: string customerName : string;
products: {
id: string;
name: string;
price: number;
}[]
products : { id: string id : string; name: string name : string; price: number price : number }[];
totalPrice: number totalPrice : number;
};
const const getOrderDetails: (orderId: string) => Result.ResultAsync<OrderDetails, "OrderNotFound" | "UserNotFound" | "ProductNotFound"> getOrderDetails = (orderId: string orderId : string): import Result Result .type ResultAsync<T, E> = Promise<Result.Result<T, E>>An asynchronous variant of
Result
, wrapped in a Promise.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const fetchData = async (): Result.ResultAsync<string, Error> => {
try {
const data = await fetch('...');
return { type: 'Success', value: await data.text() };
} catch (err) {
return { type: 'Failure', error: err as Error };
}
};
@categoryCore Types ResultAsync <type OrderDetails = {
orderId: string;
customerName: string;
products: {
id: string;
name: string;
price: number;
}[];
totalPrice: number;
}
OrderDetails , 'OrderNotFound' | 'UserNotFound' | 'ProductNotFound'> => {
return import Result Result .function pipe<Result.Result<{}, never>, Result.ResultAsync<{
order: {
id: string;
userId: string;
productIds: string[];
};
}, "OrderNotFound">, Result.ResultAsync<{
order: {
id: string;
userId: string;
productIds: string[];
};
user: {
id: string;
name: string;
};
}, "OrderNotFound" | "UserNotFound">, Result.ResultAsync<{
order: {
id: string;
userId: string;
productIds: string[];
};
user: {
id: string;
name: string;
};
products: {
id: string;
name: string;
price: number;
}[];
}, "OrderNotFound" | "UserNotFound" | "ProductNotFound">, Result.ResultAsync<{
readonly orderId: string;
readonly customerName: string;
readonly products: {
id: string;
name: string;
price: number;
}[];
readonly totalPrice: number;
}, "OrderNotFound" | ... 1 more ... | "ProductNotFound">>(a: Result.Result<...>, ab: (a: Result.Result<...>) => Result.ResultAsync<...>, bc: (b: Result.ResultAsync<...>) => Result.ResultAsync<...>, cd: (c: Result.ResultAsync<...>) => Result.ResultAsync<...>, de: (d: Result.ResultAsync<...>) => Result.ResultAsync<...>): Result.ResultAsync<...> (+25 overloads)
Applies a sequence of functions to a value, from left to right.
This utility enables function composition in a left-to-right manner.
It supports up to 26 chained functions from A through Z.
@typeParamA - The initial input value type.@typeParamB-Z - Intermediate and final function return types.@paramvalue - The initial input value.@paramfunctions - Additional unary functions composing of the previous result.@returnsThe final result after applying all functions.@exampleimport { Result } from '@praha/byethrow';
const result = Result.pipe(
2,
x => x + 1,
x => x * 3,
x => `Result: ${x}`
);
// Result: 9
@categoryUtilities pipe (
import Result Result .function do(): Result.Result<{}, never>
export do
Alias for succeed({}). Commonly used as a neutral base value in functional chains or monadic pipelines.
@exampleimport { Result } from '@praha/byethrow';
const result = Result.do();
// Result.Result<{}, never>
@categoryCreators do (),
import Result Result .function bind<"order", Result.Result<{}, never>, Result.ResultAsync<{
id: string;
userId: string;
productIds: string[];
}, "OrderNotFound">>(name: "order", fn: (a: {}) => Result.ResultAsync<{
id: string;
userId: string;
productIds: string[];
}, "OrderNotFound">): (result: Result.Result<{}, never>) => Result.ResultAsync<{
order: {
id: string;
userId: string;
productIds: string[];
};
}, "OrderNotFound"> (+1 overload)
Chains another
Result
-producing computation and merges its success value
into the existing object under the specified key.
- If the original result is a
Failure
, it is returned as-is.
- If the next result is a
Failure
, it is returned as-is.
- If both are
Success
, a new object is returned by shallow-merging:
the original success object and { [name]: nextSuccess }.
This is useful for building up objects in a compositional and type-safe way,
especially in validation or data-fetching pipelines.
@typeParamN - The key to assign the result of the fn computation.@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Success', value: { name: 1, age: 20 } }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.fail('error')),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators bind ('order', () => const fetchOrder: (orderId: string) => Result.ResultAsync<{
id: string;
userId: string;
productIds: string[];
}, "OrderNotFound">
fetchOrder (orderId: string orderId )),
import Result Result .function bind<"user", Result.ResultAsync<{
order: {
id: string;
userId: string;
productIds: string[];
};
}, "OrderNotFound">, Result.ResultAsync<{
id: string;
name: string;
}, "UserNotFound">>(name: "user", fn: (a: {
order: {
id: string;
userId: string;
productIds: string[];
};
}) => Result.ResultAsync<{
id: string;
name: string;
}, "UserNotFound">): (result: Result.ResultAsync<{
order: {
id: string;
userId: string;
productIds: string[];
};
}, "OrderNotFound">) => Result.ResultAsync<{
order: {
id: string;
userId: string;
productIds: string[];
};
user: {
id: string;
name: string;
};
}, "OrderNotFound" | "UserNotFound"> (+1 overload)
Chains another
Result
-producing computation and merges its success value
into the existing object under the specified key.
- If the original result is a
Failure
, it is returned as-is.
- If the next result is a
Failure
, it is returned as-is.
- If both are
Success
, a new object is returned by shallow-merging:
the original success object and { [name]: nextSuccess }.
This is useful for building up objects in a compositional and type-safe way,
especially in validation or data-fetching pipelines.
@typeParamN - The key to assign the result of the fn computation.@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Success', value: { name: 1, age: 20 } }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.fail('error')),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators bind ('user', ({ order: {
id: string;
userId: string;
productIds: string[];
}
order }) => const fetchUser: (userId: string) => Result.ResultAsync<{
id: string;
name: string;
}, "UserNotFound">
fetchUser (order: {
id: string;
userId: string;
productIds: string[];
}
order .userId: string userId )),
import Result Result .function bind<"products", Result.ResultAsync<{
order: {
id: string;
userId: string;
productIds: string[];
};
user: {
id: string;
name: string;
};
}, "OrderNotFound" | "UserNotFound">, Result.ResultAsync<{
id: string;
name: string;
price: number;
}[], "ProductNotFound">>(name: "products", fn: (a: {
order: {
id: string;
userId: string;
productIds: string[];
};
user: {
id: string;
name: string;
};
}) => Result.ResultAsync<{
id: string;
name: string;
price: number;
}[], "ProductNotFound">): (result: Result.ResultAsync<{
order: {
id: string;
userId: string;
productIds: string[];
};
user: {
id: string;
name: string;
};
}, "OrderNotFound" | "UserNotFound">) => Result.ResultAsync<...> (+1 overload)
Chains another
Result
-producing computation and merges its success value
into the existing object under the specified key.
- If the original result is a
Failure
, it is returned as-is.
- If the next result is a
Failure
, it is returned as-is.
- If both are
Success
, a new object is returned by shallow-merging:
the original success object and { [name]: nextSuccess }.
This is useful for building up objects in a compositional and type-safe way,
especially in validation or data-fetching pipelines.
@typeParamN - The key to assign the result of the fn computation.@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Success', value: { name: 1, age: 20 } }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.bind('age', (user) => Result.succeed(20)),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed({ name: 'Alice' }),
Result.bind('age', (user) => Result.fail('error')),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators bind ('products', ({ order: {
id: string;
userId: string;
productIds: string[];
}
order }) => const fetchProducts: (productIds: string[]) => Result.ResultAsync<{
id: string;
name: string;
price: number;
}[], "ProductNotFound">
fetchProducts (order: {
id: string;
userId: string;
productIds: string[];
}
order .productIds: string[] productIds )),
import Result Result .function map<Result.ResultAsync<{
order: {
id: string;
userId: string;
productIds: string[];
};
user: {
id: string;
name: string;
};
products: {
id: string;
name: string;
price: number;
}[];
}, "OrderNotFound" | "UserNotFound" | "ProductNotFound">, {
readonly orderId: string;
readonly customerName: string;
readonly products: {
id: string;
name: string;
price: number;
}[];
readonly totalPrice: number;
}>(fn: (a: {
order: {
id: string;
userId: string;
productIds: string[];
};
user: {
id: string;
name: string;
};
products: {
id: string;
name: string;
price: number;
}[];
}) => {
readonly orderId: string;
readonly customerName: string;
readonly products: {
id: string;
name: string;
price: number;
}[];
readonly totalPrice: number;
}): (result: Result.ResultAsync<...>) => Result.ResultAsync<...> (+1 overload)
Applies a transformation function to the success value of a
Result
or
ResultAsync
.
If the input is a
Failure
, it will be returned unchanged.
@typeParamR1 - The input Result or ResultAsync .@typeParamT2 - The transformed success value type.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(2),
Result.map((x) => x * 10),
);
// { type: 'Success', value: 20 }
@exampleFailure Case (unchanged)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.map((x) => x * 10),
);
// { type: 'Failure', error: 'error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators map (({ order: {
id: string;
userId: string;
productIds: string[];
}
order , user: {
id: string;
name: string;
}
user , products: {
id: string;
name: string;
price: number;
}[]
products }) => ({
orderId: string orderId : order: {
id: string;
userId: string;
productIds: string[];
}
order .id: string id ,
customerName: string customerName : user: {
id: string;
name: string;
}
user .name: string name ,
products: {
id: string;
name: string;
price: number;
}[]
products ,
totalPrice: number totalPrice : products: {
id: string;
name: string;
price: number;
}[]
products .Array<{ id: string; name: string; price: number; }>.reduce<number>(callbackfn: (previousValue: number, currentValue: {
id: string;
name: string;
price: number;
}, currentIndex: number, array: {
id: string;
name: string;
price: number;
}[]) => number, initialValue: number): number (+2 overloads)
Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
@paramcallbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.@paraminitialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. reduce ((sum: number sum , product: {
id: string;
name: string;
price: number;
}
product ) => sum: number sum + product: {
id: string;
name: string;
price: number;
}
product .price: number price , 0),
})),
);
};
bind はステップを 1 つずつ順番に実行します。これは、あるステップが前のステップに依存している場合に必要な動作です。
処理同士が互いに独立している場合は、次のページで紹介する sequence や collect の方が適しています。collect なら非同期処理を並列に実行することもできます。
#リファレンス
| API | 用途 |
|---|---|
| do() | 空のオブジェクトを持つ成功の Result を作成する |
| bind(name, fn) | 蓄積されたオブジェクトから計算したフィールドを追加する |
| let(name, fn) | 蓄積されたオブジェクトから計算した通常の値を追加する |
