#検証と後処理
すでに持っている値を置き換えずに、失敗しうる追加のステップを実行したいことがあります。
andThrough と orThrough はそのようなステップを実行し、ステップが成功した場合は元の Result を保持します。
#andThrough でチェックを実行する
andThrough(fn)ケースを選ぶと、その流れだけを追えますandThrough は andThen と同じように、成功値を引数に渡された関数を呼び出します。
違いは、関数が成功したときの挙動です。
- 関数が
Successを返した場合、その値は破棄され、元のSuccessが返されます。 - 関数が
Failureを返した場合、そのFailureが返されます。 - 入力が
Failureの場合、関数は呼び出されません。
import { import Result Result } from '@praha/byethrow';
const const checkPositive: (value: number) => Result.Success<void> | Result.Failure<"Must be positive"> checkPositive = (value: number value : number) => {
return 0 < value: number value ? import Result Result .function succeed(): Result.Result<void, 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 () : import Result Result .function fail<"Must be positive">(error: "Must be positive"): Result.Result<never, "Must be positive"> (+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 ('Must be positive');
};
const const passed: Result.Result<5, "Must be positive"> passed = import Result Result .function pipe<Result.Result<5, never>, Result.Result<5, "Must be positive">>(a: Result.Result<5, never>, ab: (a: Result.Result<5, never>) => Result.Result<5, "Must be positive">): Result.Result<5, "Must be positive"> (+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 succeed<5>(value: 5): Result.Result<5, 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 (5),
import Result Result .function andThrough<Result.Result<5, never>, Result.Success<void> | Result.Failure<"Must be positive">>(fn: (a: 5) => Result.Success<void> | Result.Failure<"Must be positive">): (result: Result.Result<5, never>) => Result.Result<5, "Must be positive"> (+1 overload)Runs an additional computation using the success value of a
Result
or
ResultAsync
,
but returns the original result if the additional computation is successful.
If either the original result or the side effect result is a
Failure
, that failure is returned.
Useful for running validations or side effects without altering the main result on success.
@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(5),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Success', value: 5 }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(-10),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Failure', error: 'Must be > 0' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThrough (const checkPositive: (value: number) => Result.Success<void> | Result.Failure<"Must be positive"> checkPositive ),
);
// { type: 'Success', value: 5 } - 元の値が保持される
const const rejected: Result.Result<-10, "Must be positive"> rejected = import Result Result .function pipe<Result.Result<-10, never>, Result.Result<-10, "Must be positive">>(a: Result.Result<-10, never>, ab: (a: Result.Result<-10, never>) => Result.Result<-10, "Must be positive">): Result.Result<-10, "Must be positive"> (+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 succeed<-10>(value: -10): Result.Result<-10, 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 (-10),
import Result Result .function andThrough<Result.Result<-10, never>, Result.Success<void> | Result.Failure<"Must be positive">>(fn: (a: -10) => Result.Success<void> | Result.Failure<"Must be positive">): (result: Result.Result<-10, never>) => Result.Result<-10, "Must be positive"> (+1 overload)Runs an additional computation using the success value of a
Result
or
ResultAsync
,
but returns the original result if the additional computation is successful.
If either the original result or the side effect result is a
Failure
, that failure is returned.
Useful for running validations or side effects without altering the main result on success.
@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(5),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Success', value: 5 }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(-10),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Failure', error: 'Must be > 0' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThrough (const checkPositive: (value: number) => Result.Success<void> | Result.Failure<"Must be positive"> checkPositive ),
);
// { type: 'Failure', error: 'Must be positive' }
const const skipped: Result.Result<never, "Must be positive" | "error"> skipped = import Result Result .function pipe<Result.Result<never, "error">, Result.Result<never, "Must be positive" | "error">>(a: Result.Result<never, "error">, ab: (a: Result.Result<never, "error">) => Result.Result<never, "Must be positive" | "error">): Result.Result<never, "Must be positive" | "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 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 andThrough<Result.Result<never, "error">, Result.Success<void> | Result.Failure<"Must be positive">>(fn: (a: never) => Result.Success<void> | Result.Failure<"Must be positive">): (result: Result.Result<never, "error">) => Result.Result<never, "Must be positive" | "error"> (+1 overload)Runs an additional computation using the success value of a
Result
or
ResultAsync
,
but returns the original result if the additional computation is successful.
If either the original result or the side effect result is a
Failure
, that failure is returned.
Useful for running validations or side effects without altering the main result on success.
@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(5),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Success', value: 5 }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(-10),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Failure', error: 'Must be > 0' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThrough (const checkPositive: (value: number) => Result.Success<void> | Result.Failure<"Must be positive"> checkPositive ), // 呼び出されない
);
// { type: 'Failure', error: 'error' }このため andThrough は、バリデーションや、監査ログの書き込みのような失敗しうる副作用に適しています。どちらの場合も、次のステップでは元の値が必要です。
#例:複数のバリデーション
各バリデーションは値が受け入れ可能かどうかを伝えるだけなので、単に Result.Result<void, E> を返せば十分です。
import { import Result Result } from '@praha/byethrow';
type type User = {
name: string;
age: number;
email: string;
}
User = { name: string name : string; age: number age : number; email: string email : string };
declare const const validateName: (user: User) => Result.Result<void, "InvalidName"> validateName : (user: User user : type User = {
name: string;
age: number;
email: string;
}
User ) => import Result Result .type Result<T, E> = Result.Success<T> | Result.Failure<E>A union type representing either a success or a failure.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const doSomething = (): Result.Result<number, string> => {
return Math.random() > 0.5
? { type: 'Success', value: 10 }
: { type: 'Failure', error: 'Oops' };
};
@categoryCore Types Result <void, 'InvalidName'>;
declare const const validateAge: (user: User) => Result.Result<void, "InvalidAge"> validateAge : (user: User user : type User = {
name: string;
age: number;
email: string;
}
User ) => import Result Result .type Result<T, E> = Result.Success<T> | Result.Failure<E>A union type representing either a success or a failure.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const doSomething = (): Result.Result<number, string> => {
return Math.random() > 0.5
? { type: 'Success', value: 10 }
: { type: 'Failure', error: 'Oops' };
};
@categoryCore Types Result <void, 'InvalidAge'>;
declare const const validateEmail: (user: User) => Result.Result<void, "InvalidEmail"> validateEmail : (user: User user : type User = {
name: string;
age: number;
email: string;
}
User ) => import Result Result .type Result<T, E> = Result.Success<T> | Result.Failure<E>A union type representing either a success or a failure.
@typeParamT - The type of the Success value.@typeParamE - The type of the Failure value.@exampleimport { Result } from '@praha/byethrow';
const doSomething = (): Result.Result<number, string> => {
return Math.random() > 0.5
? { type: 'Success', value: 10 }
: { type: 'Failure', error: 'Oops' };
};
@categoryCore Types Result <void, 'InvalidEmail'>;
const const validateUser: (user: User) => Result.Result<User, "InvalidName" | "InvalidAge" | "InvalidEmail"> validateUser = (user: User user : type User = {
name: string;
age: number;
email: string;
}
User ) => import Result Result .function pipe<Result.Result<User, never>, Result.Result<User, "InvalidName">, Result.Result<User, "InvalidName" | "InvalidAge">, Result.Result<User, "InvalidName" | "InvalidAge" | "InvalidEmail">>(a: Result.Result<User, never>, ab: (a: Result.Result<User, never>) => Result.Result<User, "InvalidName">, bc: (b: Result.Result<User, "InvalidName">) => Result.Result<User, "InvalidName" | "InvalidAge">, cd: (c: Result.Result<...>) => Result.Result<...>): 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 succeed<User>(value: User): Result.Result<User, 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 (user: User user ),
import Result Result .function andThrough<Result.Result<User, never>, Result.Result<void, "InvalidName">>(fn: (a: User) => Result.Result<void, "InvalidName">): (result: Result.Result<User, never>) => Result.Result<User, "InvalidName"> (+1 overload)Runs an additional computation using the success value of a
Result
or
ResultAsync
,
but returns the original result if the additional computation is successful.
If either the original result or the side effect result is a
Failure
, that failure is returned.
Useful for running validations or side effects without altering the main result on success.
@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(5),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Success', value: 5 }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(-10),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Failure', error: 'Must be > 0' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThrough (const validateName: (user: User) => Result.Result<void, "InvalidName"> validateName ),
import Result Result .function andThrough<Result.Result<User, "InvalidName">, Result.Result<void, "InvalidAge">>(fn: (a: User) => Result.Result<void, "InvalidAge">): (result: Result.Result<User, "InvalidName">) => Result.Result<User, "InvalidName" | "InvalidAge"> (+1 overload)Runs an additional computation using the success value of a
Result
or
ResultAsync
,
but returns the original result if the additional computation is successful.
If either the original result or the side effect result is a
Failure
, that failure is returned.
Useful for running validations or side effects without altering the main result on success.
@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(5),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Success', value: 5 }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(-10),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Failure', error: 'Must be > 0' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThrough (const validateAge: (user: User) => Result.Result<void, "InvalidAge"> validateAge ),
import Result Result .function andThrough<Result.Result<User, "InvalidName" | "InvalidAge">, Result.Result<void, "InvalidEmail">>(fn: (a: User) => Result.Result<void, "InvalidEmail">): (result: Result.Result<User, "InvalidName" | "InvalidAge">) => Result.Result<User, "InvalidName" | "InvalidAge" | "InvalidEmail"> (+1 overload)Runs an additional computation using the success value of a
Result
or
ResultAsync
,
but returns the original result if the additional computation is successful.
If either the original result or the side effect result is a
Failure
, that failure is returned.
Useful for running validations or side effects without altering the main result on success.
@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(5),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Success', value: 5 }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(-10),
Result.andThrough((x) => {
return x > 0 ? Result.succeed(null) : Result.fail('Must be > 0');
}),
);
// { type: 'Failure', error: 'Must be > 0' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThrough (const validateEmail: (user: User) => Result.Result<void, "InvalidEmail"> validateEmail ),
);
// 型: Result.Result<User, 'InvalidName' | 'InvalidAge' | 'InvalidEmail'>
// すべてのバリデーションを通過すれば元の user を、そうでなければ最初のエラーを返す
andThrough は最初に失敗したバリデーションで停止します。
すべてのバリデーションエラーを一度に報告したい場合は、代わりに collect を使ってください。
#orThrough で後処理を行う
orThrough(fn)ケースを選ぶと、その流れだけを追えますorThrough は、失敗に対する andThrough の対になる関数です。
エラー値を引数に渡された関数を呼び出します。典型的には、失敗した処理の後処理に使います。
- 関数が
Successを返した場合、元のFailureが返されます。 - 関数が
Failureを返した場合、その新しいFailureが返されます。 - 入力が
Successの場合、関数は呼び出されません。
import { import Result Result } from '@praha/byethrow';
const const cleanedUp: Result.Result<never, "original error"> cleanedUp = import Result Result .function pipe<Result.Result<never, "original error">, Result.Result<never, "original error">>(a: Result.Result<never, "original error">, ab: (a: Result.Result<never, "original error">) => Result.Result<never, "original error">): Result.Result<never, "original 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 fail<"original error">(error: "original error"): Result.Result<never, "original 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 ('original error'),
import Result Result .function orThrough<Result.Result<never, "original error">, Result.Result<void, never>>(fn: (a: "original error") => Result.Result<void, never>): (result: Result.Result<never, "original error">) => Result.Result<never, "original error"> (+1 overload)Runs an additional computation using the error value of a
Result
or
ResultAsync
,
but returns the original failure if the additional computation is successful.
If the original result is a
Success
, it is returned immediately without running the function.
If the original result is a
Failure
, the function is executed with the error value.
If the function returns a
Success
, the original failure is returned.
If the function returns a
Failure
, that new failure is returned.
Useful for running error recovery or fallback logic while preserving the original error on success.
@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(5),
Result.orThrough((error) => {
return Result.succeed(null);
}),
);
// { type: 'Success', value: 5 }
@exampleFailure Case (function returns a Success)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.orThrough((error) => {
console.log('Logging error:', error);
return Result.succeed(null);
}),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('original error'),
Result.orThrough((error) => {
return Result.fail('new error');
}),
);
// { type: 'Failure', error: 'new error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators orThrough (() => import Result Result .function succeed(): Result.Result<void, 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 ()),
);
// { type: 'Failure', error: 'original error' } - 元のエラーが保持される
const const cleanupFailed: Result.Result<never, "original error" | "cleanup error"> cleanupFailed = import Result Result .function pipe<Result.Result<never, "original error">, Result.Result<never, "original error" | "cleanup error">>(a: Result.Result<never, "original error">, ab: (a: Result.Result<never, "original error">) => Result.Result<never, "original error" | "cleanup error">): Result.Result<never, "original error" | "cleanup 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 fail<"original error">(error: "original error"): Result.Result<never, "original 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 ('original error'),
import Result Result .function orThrough<Result.Result<never, "original error">, Result.Result<never, "cleanup error">>(fn: (a: "original error") => Result.Result<never, "cleanup error">): (result: Result.Result<never, "original error">) => Result.Result<never, "original error" | "cleanup error"> (+1 overload)Runs an additional computation using the error value of a
Result
or
ResultAsync
,
but returns the original failure if the additional computation is successful.
If the original result is a
Success
, it is returned immediately without running the function.
If the original result is a
Failure
, the function is executed with the error value.
If the function returns a
Success
, the original failure is returned.
If the function returns a
Failure
, that new failure is returned.
Useful for running error recovery or fallback logic while preserving the original error on success.
@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(5),
Result.orThrough((error) => {
return Result.succeed(null);
}),
);
// { type: 'Success', value: 5 }
@exampleFailure Case (function returns a Success)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.orThrough((error) => {
console.log('Logging error:', error);
return Result.succeed(null);
}),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('original error'),
Result.orThrough((error) => {
return Result.fail('new error');
}),
);
// { type: 'Failure', error: 'new error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators orThrough (() => import Result Result .function fail<"cleanup error">(error: "cleanup error"): Result.Result<never, "cleanup 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 ('cleanup error')),
);
// { type: 'Failure', error: 'cleanup error' }
const const skipped: Result.Result<5, never> skipped = import Result Result .function pipe<Result.Result<5, never>, Result.Result<5, never>>(a: Result.Result<5, never>, ab: (a: Result.Result<5, never>) => Result.Result<5, never>): Result.Result<5, 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 succeed<5>(value: 5): Result.Result<5, 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 (5),
import Result Result .function orThrough<Result.Result<5, never>, Result.Result<void, never>>(fn: (a: never) => Result.Result<void, never>): (result: Result.Result<5, never>) => Result.Result<5, never> (+1 overload)Runs an additional computation using the error value of a
Result
or
ResultAsync
,
but returns the original failure if the additional computation is successful.
If the original result is a
Success
, it is returned immediately without running the function.
If the original result is a
Failure
, the function is executed with the error value.
If the function returns a
Success
, the original failure is returned.
If the function returns a
Failure
, that new failure is returned.
Useful for running error recovery or fallback logic while preserving the original error on success.
@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(5),
Result.orThrough((error) => {
return Result.succeed(null);
}),
);
// { type: 'Success', value: 5 }
@exampleFailure Case (function returns a Success)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.orThrough((error) => {
console.log('Logging error:', error);
return Result.succeed(null);
}),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('original error'),
Result.orThrough((error) => {
return Result.fail('new error');
}),
);
// { type: 'Failure', error: 'new error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators orThrough (() => import Result Result .function succeed(): Result.Result<void, 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 ()), // 呼び出されない
);
// { type: 'Success', value: 5 }orElse とは異なり、orThrough が失敗を成功に変えることはありません。
失敗が起きたからこそ必要になる処理を行いつつ、失敗そのものは呼び出し元に報告するためのものです。
#例:失敗時にロールバックする
投稿を 2 つのステップで作成する場合を考えます。まずコンテンツをアップロードし、次にデータベースにレコードを保存します。
レコードの保存に失敗した場合はアップロードしたファイルを削除すべきですが、呼び出し元には SavePostFailed エラーを返す必要があります。
import { import Result Result } from '@praha/byethrow';
declare const const uploadFile: (path: string, content: string) => Result.ResultAsync<void, "UploadFailed"> uploadFile : (path: string path : string, content: string content : 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 <void, 'UploadFailed'>;
declare const const savePost: (id: string, path: string) => Result.ResultAsync<void, "SavePostFailed"> savePost : (id: string id : string, path: string path : 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 <void, 'SavePostFailed'>;
declare const const deleteFile: (path: string) => Result.ResultAsync<void, "DeleteFileFailed"> deleteFile : (path: string path : 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 <void, 'DeleteFileFailed'>;
const const createPost: (id: string, content: string) => Result.ResultAsync<void, "UploadFailed" | "SavePostFailed" | "DeleteFileFailed"> createPost = (id: string id : string, content: string content : string) => {
const const path: string path = `/posts/${id: string id }`;
return import Result Result .function pipe<Result.ResultAsync<void, "UploadFailed">, Result.ResultAsync<void, "UploadFailed" | "SavePostFailed" | "DeleteFileFailed">>(a: Result.ResultAsync<void, "UploadFailed">, ab: (a: Result.ResultAsync<void, "UploadFailed">) => Result.ResultAsync<void, "UploadFailed" | "SavePostFailed" | "DeleteFileFailed">): Result.ResultAsync<void, "UploadFailed" | "SavePostFailed" | "DeleteFileFailed"> (+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 (
const uploadFile: (path: string, content: string) => Result.ResultAsync<void, "UploadFailed"> uploadFile (const path: string path , content: string content ),
import Result Result .function andThen<Result.ResultAsync<void, "UploadFailed">, Result.ResultAsync<void, "SavePostFailed" | "DeleteFileFailed">>(fn: (a: void) => Result.ResultAsync<void, "SavePostFailed" | "DeleteFileFailed">): (result: Result.ResultAsync<void, "UploadFailed">) => Result.ResultAsync<void, "UploadFailed" | "SavePostFailed" | "DeleteFileFailed"> (+1 overload)Chains the next computation using the success value of a
Result
or
ResultAsync
.
If the original result is a
Failure
, it is returned unchanged.
Otherwise, the provided function is called, and its result is returned as-is.
@typeParamR1 - The input Result or ResultAsync .@typeParamR2 - The result type returned by fn.@exampleSuccess Case
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(3),
Result.andThen((x) => Result.succeed(x * 2)),
);
// { type: 'Success', value: 6 }
@exampleFailure Case (input is a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.andThen((x) => Result.succeed(x * 2)),
);
// result: { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.succeed(3),
Result.andThen((x) => Result.fail('error: ' + x)),
);
// result: { type: 'Failure', error: 'error: 3' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators andThen (() => import Result Result .function pipe<Result.ResultAsync<void, "SavePostFailed">, Result.ResultAsync<void, "SavePostFailed" | "DeleteFileFailed">>(a: Result.ResultAsync<void, "SavePostFailed">, ab: (a: Result.ResultAsync<void, "SavePostFailed">) => Result.ResultAsync<void, "SavePostFailed" | "DeleteFileFailed">): Result.ResultAsync<void, "SavePostFailed" | "DeleteFileFailed"> (+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 (
const savePost: (id: string, path: string) => Result.ResultAsync<void, "SavePostFailed"> savePost (id: string id , const path: string path ),
// savePost が失敗したときだけ実行される
import Result Result .function orThrough<Result.ResultAsync<void, "SavePostFailed">, Result.ResultAsync<void, "DeleteFileFailed">>(fn: (a: "SavePostFailed") => Result.ResultAsync<void, "DeleteFileFailed">): (result: Result.ResultAsync<void, "SavePostFailed">) => Result.ResultAsync<void, "SavePostFailed" | "DeleteFileFailed"> (+1 overload)Runs an additional computation using the error value of a
Result
or
ResultAsync
,
but returns the original failure if the additional computation is successful.
If the original result is a
Success
, it is returned immediately without running the function.
If the original result is a
Failure
, the function is executed with the error value.
If the function returns a
Success
, the original failure is returned.
If the function returns a
Failure
, that new failure is returned.
Useful for running error recovery or fallback logic while preserving the original error on success.
@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(5),
Result.orThrough((error) => {
return Result.succeed(null);
}),
);
// { type: 'Success', value: 5 }
@exampleFailure Case (function returns a Success)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('error'),
Result.orThrough((error) => {
console.log('Logging error:', error);
return Result.succeed(null);
}),
);
// { type: 'Failure', error: 'error' }
@exampleFailure Case (function returns a Failure)
import { Result } from '@praha/byethrow';
const result = Result.pipe(
Result.fail('original error'),
Result.orThrough((error) => {
return Result.fail('new error');
}),
);
// { type: 'Failure', error: 'new error' }
@seepipe - It is recommended to use this function with the pipe function for better readability and composability.@categoryCombinators orThrough (() => const deleteFile: (path: string) => Result.ResultAsync<void, "DeleteFileFailed"> deleteFile (const path: string path )),
)),
);
};
// 型: Result.ResultAsync<void, 'UploadFailed' | 'SavePostFailed' | 'DeleteFileFailed'>orThrough を savePost の直後に置いているため、後処理は保存に失敗したときだけ実行され、アップロード自体が失敗したときには実行されません。
#リファレンス
| API | 用途 |
|---|---|
| andThrough(fn) | 成功時にステップを実行し、元の値を保持する |
| orThrough(fn) | 失敗時にステップを実行し、元のエラーを保持する |
