01エラーは値になる
関数は throw する代わりに Result<T, E> を返します。Success は値を、Failure はエラーを持ち、型検査が両方を処理していることを保証します。
詳しく見るA lightweight Result type package
throw にさよなら、型安全な Result へ
npm install @praha/byethrow1const parseJson = (text: string) => {2 return JSON.parse(text); // may throw, but the type won't say3};4 5try {6 const data = parseJson('{ "answer": 21 }');7 console.log(data.answer * 2); // data: any8} catch (error) {9 // error: unknown. What could it be?10}失敗は値として表現されます。見えない throw も、忘れられた catch も、本番環境での驚きもありません。
関数は throw する代わりに Result<T, E> を返します。Success は値を、Failure はエラーを持ち、型検査が両方を処理していることを保証します。
詳しく見る{ type: 'Success', value: 42 }{ type: 'Failure', error: NotFound }失敗すると残りのステップはすべてスキップされます
no-throw-in-callbackexpect(result).toBeSuccess()byethrow-docs init claudeこれらのコードはドキュメントのビルドごとに型検査されています。識別子にカーソルを合わせると、コンパイラが推論した型を確認できます。
Result.fn で、throw する関数や非同期関数を Result を返す関数に変換します。
import { import Result Result } from '@praha/byethrow';
type type User = {
id: string;
name: string;
}
User = { id: string id : string; name: string name : string };
const const fetchUser: (id: string) => Result.ResultAsync<User, Error> fetchUser = import Result Result .function fn<(id: string) => Promise<User>, Error>(options: {
try: (id: string) => Promise<User>;
catch: (error: unknown) => Error;
}): (id: string) => Result.ResultAsync<User, Error> (+3 overloads)
Wraps a function that may throw and returns a new function that returns a
Result
or
ResultAsync
.
You can use either a custom catch handler or rely on the safe: true option
to assume the function cannot throw.
fn ({
try: (id: string) => Promise<User> try : async (id: string id : string): interface Promise<T>Represents the completion of an asynchronous operation
Promise <type User = {
id: string;
name: string;
}
User > => {
const const response: Response response = await function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> fetch (`/api/users/${id: string id }`);
if (!const response: Response response .Response.ok: booleanThe ok read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not.
ok ) throw new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error (`HTTP ${const response: Response response .Response.status: numberThe status read-only property of the Response interface contains the HTTP status codes of the response.
status }`);
return const response: Response response .Body.json(): Promise<any> json ();
},
catch: (error: unknown) => Error catch : (error: unknown error ) => new var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error ('Failed to fetch user', { ErrorOptions.cause?: unknown cause : error: unknown error }),
});
const const result: Result.Result<User, Error> result = await const fetchUser: (id: string) => Result.ResultAsync<User, Error> fetchUser ('u_123');