ホーム 全セッション S01

必要な情報が欠けた状態を型で排除する

4 / 10 目安 1.5分

ページ一覧

事前知識: 状態ごとに別の型を定義すると、必要な情報が欠けた予約は、型検査のときに報告されます。

遷移関数の引数を絞るには、来院済みなどの状態ごとの型が必要です。S00 のコードとこの Session の開始コードを比較し、状態ごとの型が何を防ぐかを確認します。

予約の値に、診察中なのに獣医師がいないような、業務上ありえない組み合わせを作成できる場合、その値を受け取る関数は、項目が存在しない可能性を毎回検証する必要があります。状態ごとに別の型を定義すると、そのような値を含むコードは、型検査のときに報告されます。

examples/session-00/src/domain/appointment/appointment.ts S00 のコード

export type Appointment = Readonly<{
  appointmentId: string;
  petId: string;
  petName: string;
  ownerId: string;
  ownerName: string;
  ownerEmail: string;
  ownerPhone: string;
  scheduledAt: string;
  reason: string;
  status: string;
  checkedInAt?: string;
  veterinarianId?: string;
  examinationStartedAt?: string;
  examId?: string;
  examinationCompletedAt?: string;
  diagnosis?: unknown;
  treatment?: unknown;
  items?: unknown;
  amount?: unknown;
  paidAt?: string;
  cancelReason?: string;
}>;

export type AppointmentExtra = Partial<Omit<Appointment, "appointmentId">>;

export type BookAppointmentInput = Omit<Appointment, "status">;

export const bookAppointment = (input: BookAppointmentInput): Appointment => ({
  ...input,
  status: "scheduled",
});

export const updateStatus = (
  appointment: Appointment,
  status: string,
  extra?: AppointmentExtra,
): Appointment => ({ ...appointment, ...extra, status });

examples/session-00/src/domain/appointment/statusLabel.ts S00 のコード

import type { Appointment } from "./appointment.js";

const statusLabels: Record<string, string> = {
  scheduled: "予約済み",
  "checked-in": "来院済み",
  "in-examination": "診察中",
  "awaiting-payment": "会計待ち",
  paid: "会計済み",
  canceled: "キャンセル",
};

export const toStatusLabel = (appointment: Appointment): string => {
  const label = Object.hasOwn(statusLabels, appointment.status)
    ? statusLabels[appointment.status]
    : undefined;

  return label ?? appointment.status;
};

examples/session-01/src/domain/appointment/appointment.ts S01 の開始コード

export type CancellationReason = string;

export type Scheduled = Readonly<{
  kind: "Scheduled";
  appointmentId: string;
  petId: string;
  ownerId: string;
  scheduledAt: string;
  reason: string;
}>;

export type CheckedIn = Readonly<{
  kind: "CheckedIn";
  appointmentId: string;
  petId: string;
  ownerId: string;
  scheduledAt: string;
  reason: string;
  checkedInAt: string;
}>;

export type InExamination = Readonly<{
  kind: "InExamination";
  appointmentId: string;
  petId: string;
  ownerId: string;
  scheduledAt: string;
  reason: string;
  checkedInAt: string;
  veterinarianId: string;
  examinationStartedAt: string;
}>;

export type AwaitingPayment = Readonly<{
  kind: "AwaitingPayment";
  appointmentId: string;
  petId: string;
  ownerId: string;
  scheduledAt: string;
  reason: string;
  checkedInAt: string;
  veterinarianId: string;
  examinationStartedAt: string;
  examId: string;
  examinationCompletedAt: string;
}>;

export type Paid = Readonly<{
  kind: "Paid";
  appointmentId: string;
  petId: string;
  ownerId: string;
  scheduledAt: string;
  reason: string;
  checkedInAt: string;
  veterinarianId: string;
  examinationStartedAt: string;
  examId: string;
  examinationCompletedAt: string;
  diagnosis: string;
  treatment: string;
  amount: number;
  paidAt: string;
}>;

export type Canceled = Readonly<{
  kind: "Canceled";
  appointmentId: string;
  petId: string;
  ownerId: string;
  scheduledAt: string;
  reason: CancellationReason;
  canceledAt: string;
}>;

export type Appointment =
  | Scheduled
  | CheckedIn
  | InExamination
  | AwaitingPayment
  | Paid
  | Canceled;

export type CompleteExaminationInput = Readonly<{ examId: string }>;

export type RecordPaymentInput = Readonly<{
  diagnosis: string;
  treatment: string;
  amount: number;
}>;

examples/session-01/src/domain/appointment/statusLabel.ts S01 の開始コード

import type { Appointment } from "./appointment.js";

export const toStatusLabel = (appointment: Readonly<{ kind: string }>): string => {
  switch (appointment.kind) {
    case "Scheduled":
      return "予約済み";
    case "CheckedIn":
      return "来院済み";
    case "InExamination":
      return "診察中";
    case "AwaitingPayment":
      return "会計待ち";
    case "Paid":
      return "会計済み";
    case "Canceled":
      return "キャンセル";
    default:
      return "不明";
  }
};

export type StatusLabelAppointment = Appointment;

examples/session-01/src/domain/appointment/transitions.ts S01 の開始コード

import type {
  Appointment,
  CancellationReason,
  CompleteExaminationInput,
  RecordPaymentInput,
} from "./appointment.js";

const requireKind = (appointment: Appointment, allowedKinds: ReadonlyArray<Appointment["kind"]>): void => {
  if (!allowedKinds.includes(appointment.kind)) {
    throw new Error(`Cannot transition from ${appointment.kind}`);
  }
};

export const checkIn = (appointment: Appointment, checkedInAt: string): Appointment => {
  requireKind(appointment, ["Scheduled"]);
  return ({ ...appointment, kind: "CheckedIn", checkedInAt }) as Appointment;
};

export const startExamination = (
  appointment: Appointment,
  veterinarianId: string,
  examinationStartedAt: string,
): Appointment => {
  requireKind(appointment, ["CheckedIn"]);
  return ({ ...appointment, kind: "InExamination", veterinarianId, examinationStartedAt }) as Appointment;
};

export const completeExamination = (
  appointment: Appointment,
  input: CompleteExaminationInput,
  examinationCompletedAt: string,
): Appointment => {
  requireKind(appointment, ["InExamination"]);
  return ({
    ...appointment,
    ...input,
    kind: "AwaitingPayment",
    examinationCompletedAt,
  }) as Appointment;
};

export const recordPayment = (
  appointment: Appointment,
  input: RecordPaymentInput,
  paidAt: string,
): Appointment => {
  requireKind(appointment, ["AwaitingPayment"]);
  return ({ ...appointment, ...input, kind: "Paid", paidAt }) as Appointment;
};

export const cancel = (
  appointment: Appointment,
  reason: CancellationReason | undefined,
  canceledAt: string,
): Appointment => {
  requireKind(appointment, ["Scheduled", "CheckedIn"]);
  if (reason === undefined) throw new Error("Cancellation reason is required");
  return ({ ...appointment, kind: "Canceled", reason, canceledAt }) as Appointment;
};

説明用のコード: このコマにはありません ファイルにはない、短い例です

S00 のコード declare const は、値があるものとして型検査だけに伝える書き方です。

declare const checkedIn: Appointment;
const broken = updateStatus(
  checkedIn,
  "in-examination",
);

! 型検査: エラーなし

診察中の値に、次の項目がありません。

veterinarianId examinationStartedAt

業務上 値(共通の項目は省略) S00 のコード 型検査
業務上ありえる 獣医師と開始時刻がそろっている
{ status: "in-examination", veterinarianId: "vet-001", examinationStartedAt: "10:00" }
型検査: 受け入れる
業務上ありえない 診察中なのに、獣医師も開始時刻もない
{ status: "in-examination" }
! 型検査: 受け入れる
業務上ありえない 状態の綴りが誤っている
{ status: "in-examintion" }
! 型検査: 受け入れる

S01 の開始コード declare const は、値があるものとして型検査だけに伝える書き方です。

declare const checkedIn: CheckedIn;
const broken: InExamination = {
  ...checkedIn,
  kind: "InExamination",
};

× 型検査: エラー

診察中の値に、次の項目がありません。

veterinarianId examinationStartedAt

業務上 値(共通の項目は省略) S01 の開始コード 型検査
業務上ありえる 獣医師と開始時刻がそろっている
{ kind: "InExamination", veterinarianId: "vet-001", examinationStartedAt: "10:00" }
✓ 型検査: 受け入れる
業務上ありえない 診察中なのに、獣医師も開始時刻もない
{ kind: "InExamination" }
× 型検査: エラー
業務上ありえない 状態の綴りが誤っている
{ kind: "InExamintion" }
× 型検査: エラー
  1. S00 のコードの Appointment は、状態を string で持ちます。診察中にだけ必要な veterinarianId と examinationStartedAt は、? を付けて省略できます。Readonly<{…}> は、項目を書き換えられない型にします。

  2. S00 の updateStatus は、状態を文字列で受け取ります。診察中なのに獣医師も開始時刻もない予約を作る呼び出しが、型検査を通ります。

  3. この型は、業務上ありえない組み合わせを、すべて受け入れます。

  4. S01 の開始コードは、状態ごとに別の型を持ちます。S00 の status: "in-examination" に当たる値は kind: "InExamination" で、値を型の名前と同じ綴りにしています。InExamination では veterinarianId と examinationStartedAt が必須です。型の定義はここまでで完了しており、残りは遷移関数の引数です。

  5. ...checkedIn は、checkedIn の項目のコピーです。この値は、S00 のような関数の呼び出しではなく、オブジェクトの定義です。同じ状況の値を InExamination として定義すると、veterinarianId と examinationStartedAt がないことを、型検査が報告します。実行前に検出できます。

  6. 同じ3つの値のうち、型検査が受け入れるのは、業務上ありえる1つだけです。業務上ありえない値を、型検査のときに報告できる形にする考え方です。