ホーム 全セッション S02

型検査による追加漏れの検出

6 / 11 目安 1.5分

ページ一覧

解決策: default で assertNever を呼び、追加漏れを型検査で検出します。

修正点は3つです。assertNever の追加、引数の型を Appointment にすること、default で呼ぶことです。assertNever は never 型の引数を受け取り、例外を投げます。返す値の候補が0個であるため、戻り値の型も never です。never 型の値は string の戻り値としても扱えます。

  1. ▲ 修正前 examples/session-02/src/domain/appointment/statusLabel.ts(抜粋)
    export const toStatusLabel = (appointment: Readonly<{ kind: string }>): string => {
      switch (appointment.kind) {
        …
        default:
          return "不明";
      }
    };
    ● 修正後 examples/session-02-solution/src/domain/appointment/statusLabel.ts(抜粋)
    const assertNever = (value: never): never => {
      throw new Error(`Unknown appointment status: ${JSON.stringify(value)}`);
    };
    export const toStatusLabel = (appointment: Appointment): string => {
      switch (appointment.kind) {
        …
        default:
          return assertNever(appointment);
      }
    };

    左が修正前、右が修正後です。線を付けた行が、3つの修正点です。assertNever は、受け取った値を JSON にしてメッセージへ含め、例外を投げます。

  2. ● 状態の追加前 src/domain/appointment/statusLabel.ts(抜粋)
    const assertNever = (value: never): never => {
      …
    };
    export const toStatusLabel = (appointment: Appointment): string => {
      switch (appointment.kind) {
        …
        default:
          return assertNever(appointment);
      }
    };
    • Scheduled ✓
    • CheckedIn ✓
    • InExamination ✓
    • AwaitingPayment ✓
    • Paid ✓
    • Canceled ✓

    残りの候補: 0 個

    ✓ appointment は never 型です。assertNever に渡せるため、型検査を通過します。

    6個の case をすべて処理すると、default に残る候補は0個です。線を付けた行で、appointment は never 型になり、assertNever に渡せます。

  3. NoShow を追加した変更 説明用(教材のコードにはありません) src/domain/appointment/appointment.ts(抜粋)
    export type Appointment =
      …
      | Canceled
      | NoShow;
    ▲ NoShow の追加後 src/domain/appointment/statusLabel.ts(抜粋)
    const assertNever = (value: never): never => {
      …
    };
    export const toStatusLabel = (appointment: Appointment): string => {
      switch (appointment.kind) {
        …
        default:
          return assertNever(appointment);
      }
    };
    • Scheduled ✓
    • CheckedIn ✓
    • InExamination ✓
    • AwaitingPayment ✓
    • Paid ✓
    • Canceled ✓
    • × NoShow

    残りの候補: 1 個(NoShow)

    ▲ appointment は NoShow 型です。型エラーになるため、型検査で検出されます。

    default の行で報告される型エラー Argument of type 'NoShow' is not assignable to parameter of type 'never'. 意味: NoShow 型の値を、never 型の引数に渡せません。

    NoShow を追加しても対応する case が漏れていると、default に残る候補は NoShow の1個です。この型エラーは、エディタの赤線と、型検査のコマンドの両方に表示されます。