0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【TypeScript】Conditional Type

Posted at

はじめに

こんにちは。アメリカ在住で独学エンジニアを目指している Taira です。

TypeScriptを使っていると「ある条件によって型を切り替えたい」と思うことがあります。
例えば、フォームが「新規作成」か「編集」かによって送信するデータ型を変えたいケースです。
そんなときに便利なのが Conditional Type(条件付き型) です。


基本構文

Conditional Type の基本構文は以下の通りです:

T extends U ? X : Y

意味は次のようになります:

  • TU に代入可能なら → 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 の形で条件分岐
  • フォームのモード切り替えなど、実務で使うと型安全性がグッと高まる
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?