修正点は3つです。assertNever の追加、引数の型を Appointment にすること、default で呼ぶことです。assertNever は never 型の引数を受け取り、例外を投げます。返す値の候補が0個であるため、戻り値の型も never です。never 型の値は string の戻り値としても扱えます。
-
▲ 修正前 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 にしてメッセージへ含め、例外を投げます。 -
● 状態の追加前 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に渡せます。 -
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個です。この型エラーは、エディタの赤線と、型検査のコマンドの両方に表示されます。