#はじめに
@praha/byethrow は、JavaScript と TypeScript に Result 型をもたらす、軽量でツリーシェイキング可能なライブラリです。
関数は例外を投げる代わりに、成功または失敗のどちらかを表す値を返します。
失敗の可能性が型の一部になるため、それが処理されていることをコンパイラが保証できます。
#ひと目でわかる byethrow
throw を使う場合、関数のシグネチャからはその関数がどのように失敗するのかがわかりません。
// 例外を投げる?どんなエラー?シグネチャからはわからない
const const findUser: (id: string) => Promise<User> findUser = async (id: string id : string): interface Promise<T>Represents the completion of an asynchronous operation
Promise <type User = {
id: string;
name: string;
}
User > => {
// ...
};byethrow を使うと、想定されるすべての失敗が戻り値の型に現れ、try/catch を使わずに Result を一歩ずつ組み合わせられます。
import { import Result Result } from '@praha/byethrow';
const const validateId: (id: string) => Result.Failure<InvalidIdError> | Result.Success<string> validateId = (id: string id : string) => {
if (!id: string id .String.startsWith(searchString: string, position?: number): booleanReturns true if the sequence of elements of searchString converted to a String is the
same as the corresponding elements of this object (converted to a String) starting at
position. Otherwise returns false.
startsWith ('u')) {
return import Result Result .function fail<InvalidIdError>(error: InvalidIdError): Result.Result<never, InvalidIdError> (+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 (new constructor InvalidIdError(message?: string, options?: ErrorOptions): InvalidIdError (+1 overload) InvalidIdError ());
}
return import Result Result .function succeed<string>(value: string): Result.Result<string, 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 (id: string id );
};
const const findUser: (id: string) => Result.ResultAsync<User, UserNotFoundError> findUser = async (id: string id : 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 User = {
id: string;
name: string;
}
User , class UserNotFoundError UserNotFoundError > => {
const const user: User | undefined user = await const db: {
findUser: (id: string) => Promise<User | undefined>;
}
db .findUser: (id: string) => Promise<User | undefined> findUser (id: string id );
if (!const user: User | undefined user ) {
return import Result Result .function fail<UserNotFoundError>(error: UserNotFoundError): Result.Result<never, UserNotFoundError> (+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 (new constructor UserNotFoundError(message?: string, options?: ErrorOptions): UserNotFoundError (+1 overload) UserNotFoundError ());
}
return 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 (const user: User user );
};
const const result: Result.Result<User, InvalidIdError | UserNotFoundError> result = await import Result Result .function pipe<Result.Result<"u123", never>, Result.Result<string, InvalidIdError>, Result.ResultAsync<User, InvalidIdError | UserNotFoundError>>(a: Result.Result<"u123", never>, ab: (a: Result.Result<"u123", never>) => Result.Result<string, InvalidIdError>, bc: (b: Result.Result<string, InvalidIdError>) => Result.ResultAsync<User, InvalidIdError | UserNotFoundError>): 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 succeed<"u123">(value: "u123"): Result.Result<"u123", 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 ('u123'),
import Result Result .function andThen<Result.Result<"u123", never>, Result.Failure<InvalidIdError> | Result.Success<string>>(fn: (a: "u123") => Result.Failure<InvalidIdError> | Result.Success<string>): (result: Result.Result<"u123", never>) => Result.Result<string, InvalidIdError> (+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 (const validateId: (id: string) => Result.Failure<InvalidIdError> | Result.Success<string> validateId ),
import Result Result .function andThen<Result.Result<string, InvalidIdError>, Result.ResultAsync<User, UserNotFoundError>>(fn: (a: string) => Result.ResultAsync<User, UserNotFoundError>): (result: Result.Result<string, InvalidIdError>) => Result.ResultAsync<User, InvalidIdError | UserNotFoundError> (+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 (const findUser: (id: string) => Result.ResultAsync<User, UserNotFoundError> findUser ),
);
// 型: Result.Result<User, InvalidIdError | UserNotFoundError>#特徴
- ツリーシェイキング対応:すべての関数が独立したエクスポートなので、バンドルには実際に使う関数だけが含まれます。
- プレーンオブジェクト:
Resultはクラスのインスタンスではなく、ただのプレーンオブジェクトです。ログ出力、シリアライズ、デバッグが簡単です。 - 同期と非同期で同じ API:すべての関数が
Result<T, E>とPromise<Result<T, E>>の両方を受け付けます。 - 合成しやすい設計:
pipeと、map・andThen・andThroughなどの関数を組み合わせて、読みやすいパイプラインを構築できます。 - 機能を絞った API:エイリアスや紛らわしいバリエーションのない、Result を中心とした少数の関数で構成されています。
- 完全に型安全:すべての関数に型テストがあり、成功値とエラーの型が正確に推論されます。
#byethrow が役立つ場面
byethrow は、アプリケーションの通常の動作の一部として起こる失敗に最も適しています。例えば次のような場面です。
- API 呼び出し:ネットワークエラーやサーバーエラーで失敗する可能性がある場合
- 入力のバリデーション:問題点を 1 つ、またはすべてユーザーに伝えたい場合
- ファイル操作:ファイルが存在しない、権限がないなどの理由で失敗する可能性がある場合
- パーサー:不正な入力を適切に拒否する必要がある場合
- ビジネスルール:「投稿はすでに削除されている」「ユーザーに権限がない」といったルールを扱う場合
起こり得るすべてのエラーを Result で包む必要はありません。
データベース接続の切断のような本当に想定外のエラーは、これまで通り throw して、インフラ側で処理できます。
その線引きについては Result vs throw を参照してください。
#次のステップ
- byethrow を選ぶ理由:byethrow が解決する課題と、他のアプローチとの比較
- クイックスタート:パッケージをインストールして、
Resultを使った最初のコードを書く - チュートリアル:すべての関数を一歩ずつ学ぶ
