#Building Objects
Sometimes you need several values, each produced by an operation that can fail, and later steps depend on earlier ones.
The do / bind / let pattern collects these values into a single object, one field at a time.
#Starting with do
do creates a Success holding an empty object. It is the starting point of the pattern:
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: {} }#Adding Fields with bind
bind(name, fn)Select a case to follow its pathbind(name, fn) adds a field to the accumulated object:
- It calls
fnwith the object accumulated so far. - If
fnreturns aSuccess, its value is added to the object undername. - If
fnreturns aFailure, the pipeline stops and thatFailureis returned.
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 } }#Using Previous Values
The key feature of bind is that each step can use the fields added before it:
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 )), // Uses `user`
);
// Type: Result.Result<{ user: { id: string; profileId: string }; profile: { bio: string } }, 'UserNotFound' | 'ProfileNotFound'>#Failures Short-Circuit
If any bind fails, the remaining steps are skipped:
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!')), // Fails here
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)), // Skipped
);
// { type: 'Failure', error: 'Error!' }#Adding Plain Values with let
let(name, fn)Select a case to follow its pathSome fields are computed from the fields added so far and cannot fail.
let(name, fn) adds the value returned by fn directly, so you don't need to wrap it in 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 } }This is the same as Result.bind('total', ({ price, quantity }) => Result.succeed(price * quantity)), but it shows at a glance that the step cannot fail.
let does not await a Promise for you, and it has no way to represent a failure.
If the value comes from an async operation or one that can fail, use bind with a function that returns a Result or ResultAsync.
#Example: Fetching Related Data
When one piece of data is needed to fetch another, bind keeps every intermediate value available until the end:
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 runs its steps one after another, which is necessary when a step depends on a previous one.
If the operations are independent of each other, sequence or collect on the next page is a better fit, since collect can also run async operations in parallel.
#References
| API | Purpose |
|---|---|
| do() | Create a success result holding an empty object |
| bind(name, fn) | Add a field computed from the accumulated object |
| let(name, fn) | Add a plain value computed from the accumulated object |
