問題一覧に戻る
中級高度な型
問題38: Extract'<'T, U'>'
Extract'<'T, U'>'ユーティリティ型を使って、Union型から特定の型だけを抽出する方法を学びます。条件に合う型だけを選択して新しい型を作成できます。
// Union型の定義
type AllTypes = string | number | boolean | null | undefined;
type Primitives = string | number | boolean;
// Extract型の使用
type ExtractedPrimitives = <AllTypes, Primitives>;
const value: ExtractedPrimitives = "hello";
// 判別可能なUnionでの使用
type EventHandler =
| { type: "click"; handler: () => void }
| { type: "change"; handler: (value: string) => void }
| { type: "submit"; handler: (data: FormData) => void };
type ClickHandler = <EventHandler, { type: "click" }>;