はじめに
こんにちは。アメリカ在住で独学エンジニアを目指している Taira です。
TypeScriptを使っていると「ある条件によって型を切り替えたい」と思うことがあります。
例えば、フォームが「新規作成」か「編集」かによって送信するデータ型を変えたいケースです。
そんなときに便利なのが Conditional Type(条件付き型) です。
基本構文
Conditional Type の基本構文は以下の通りです:
T extends U ? X : Y
意味は次のようになります:
-
TがUに代入可能なら →X - そうでなければ →
Y
実践例:フォームモードによって型を切り替える
type StudentFormMode = "create" | "edit";
type CreateStudentPayload = {
name: string;
email: string;
};
type EditStudentPayload = {
id: number; // 既存データを更新するためにIDが必要
name?: string;
email?: string;
};
// Conditional TypeでモードごとにPayloadを切り替え
type PayloadByMode<T extends StudentFormMode> =
T extends "edit" ? EditStudentPayload : CreateStudentPayload;
この型を使うと、モードに応じたペイロードを安全に定義できます:
const createPayload: PayloadByMode<"create"> = {
name: "Taro",
email: "taro@example.com",
};
// ✅ CreateStudentPayload なのでOK
const editPayload: PayloadByMode<"edit"> = {
id: 1,
name: "Jiro",
};
// ✅ EditStudentPayload なのでOK
const invalidEditPayload: PayloadByMode<"edit"> = {
name: "Jiro",
};
// ❌ idが必須なのでエラー
これで「モードとペイロードの不整合」をコンパイル時に防げます。
まとめ
- Conditional Typeは「型のif文」のように書ける
-
T extends U ? X : Yの形で条件分岐 - フォームのモード切り替えなど、実務で使うと型安全性がグッと高まる