For AI agents: the complete documentation index is available at /byethrow/ja/llms.txt, the full documentation bundle is available at /byethrow/ja/llms-full.txt, and this page is available as Markdown at /byethrow/ja/index.md.
  • 日本語
  • byethrow

    A lightweight Result type package

    throw にさよなら、型安全な Result へ

    npm install @praha/byethrow
    any
    1const 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}
    Uncheckedエラーが型に現れません
    Why byethrow

    コンパイラが理解できるエラーハンドリング

    失敗は値として表現されます。見えない throw も、忘れられた catch も、本番環境での驚きもありません。

    Result<T, E>Success { value: T }Failure { error: E }

    01エラーは値になる

    関数は throw する代わりに Result<T, E> を返します。Success は値を、Failure はエラーを持ち、型検査が両方を処理していることを保証します。

    詳しく見る
    { type: 'Success', value: 42 }
    { type: 'Failure', error: NotFound }
    JSON.stringify ✓structuredClone ✓no instanceof

    02ただのプレーンオブジェクト

    クラスも instanceof も隠れた状態もありません。ログに出す、シリアライズする、通信で送る、すべてそのままできます。

    詳しく見る
    Result<T, E>ResultAsync<T, E>map(fn)UU

    03同期も非同期も同じ API

    すべての関数が Result と Promise<Result> の両方を受け付けます。覚える API はひとつだけです。

    詳しく見る
    succeed(id)andThen(findUser)map(toDto)unwrap()

    失敗すると残りのステップはすべてスキップされます

    04合成を前提にした設計

    pipe で処理をつなげます。各関数は成功時だけ実行され、失敗はそのまま末尾まで流れていきます。

    詳しく見る
    pipesucceedfailmapandThenorElsetryfncollectunwrapsequenceparse
    バンドルに含まれる取り除かれる

    05使う分だけをバンドル

    各関数は独立したエクスポートなので、呼ばれない関数はバンドラーが取り除きます。

    詳しく見る
    Lint プラグインno-throw-in-callback
    テストマッチャーexpect(result).toBeSuccess()
    AI アシスタント向けドキュメントbyethrow-docs init claude

    06周辺ツールも揃っています

    Lint プラグイン、テストマッチャー、AI アシスタント向けドキュメントで、チーム全体が同じパターンを保てます。

    詳しく見る
    In practice

    すべての失敗が、型に現れる

    これらのコードはドキュメントのビルドごとに型検査されています。識別子にカーソルを合わせると、コンパイラが推論した型を確認できます。

    Result.fn で、throw する関数や非同期関数を Result を返す関数に変換します。

    fetch-user.tsホバーで型を確認
    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.

    @typeParamT - The function type to execute (sync or async) or a Promise type.@typeParamE - The error type to return if catch is used.@returnsA new function that returns a Result or ResultAsync wrapping the original function's return value or the caught error.@example

    Sync try-catch

    import { Result } from '@praha/byethrow';
    
    const fn = Result.fn({
    try: (x: number) => {
    if (x < 0) throw new Error('Negative!');
    return x * 2;
    },
    catch: (error) => new Error('Oops!', { cause: error }),
    });
    
    const result = fn(5); // Result.Result<number, Error>
    @example

    Sync safe

    import { Result } from '@praha/byethrow';
    
    const fn = Result.fn({
    safe: true,
    try: (x: number) => x + 1,
    });
    
    const result = fn(1); // Result.Result<number, never>
    @example

    Async try-catch

    import { Result } from '@praha/byethrow';
    
    const fn = Result.fn({
    try: async (id: string) => await fetch(`/api/data/${id}`),
    catch: (error) => new Error('Oops!', { cause: error }),
    });
    
    const result = await fn('abc'); // Result.ResultAsync<Response, Error>
    @example

    Async safe

    import { Result } from '@praha/byethrow';
    
    const fn = Result.fn({
    safe: true,
    try: async () => await Promise.resolve('ok'),
    });
    
    const result = await fn(); // Result.ResultAsync<string, never>
    @categoryCreators
    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: boolean

    The 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.

    MDN Reference

    ok
    ) throw new
    var Error: ErrorConstructor
    new (message?: string, options?: ErrorOptions) => Error (+1 overload)
    Error
    (`HTTP ${
    const response: Response
    response
    .
    Response.status: number

    The status read-only property of the Response interface contains the HTTP status codes of the response.

    MDN Reference

    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');
    はじめよう

    throw に、さよならを。

    パッケージをインストールして、最初の関数を Result を返す形に書き換えてみましょう。1 分もかかりません。

    npm install @praha/byethrow