TypeScript Pick<T, K>ユーティリティ型の解説
Pick<T, K>が別の型から特定のプロパティを選択して型を作成する方法を学びます。サブセット、DTO、コンポーネントpropsの実践的な例を紹介します。
Object Types
詳細な説明
Pick<T, K>の理解
Pick<T, K>はユニオンKに含まれるキーのプロパティを型Tから選択して型を構築します。データベーステーブルから特定のカラムを選択する型レベルの操作に相当します。
構文
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
基本的な例
interface User {
id: number;
name: string;
email: string;
password: string;
avatar: string;
createdAt: Date;
}
type UserPreview = Pick<User, "id" | "name" | "avatar">;
// 以下と同等:
// {
// id: number;
// name: string;
// avatar: string;
// }
実践パターン: APIレスポンスの整形
// 完全なデータベースモデル
interface Product {
id: string;
name: string;
price: number;
cost: number;
inventory: number;
supplier: string;
internalNotes: string;
}
// パブリックAPIレスポンス -- 内部フィールドを除外
type PublicProduct = Pick<Product, "id" | "name" | "price">;
// 管理者APIレスポンス -- 在庫を含む
type AdminProduct = Pick<Product, "id" | "name" | "price" | "inventory" | "supplier">;
PickとOmitの比較
PickとOmitは補完的です:
- 大きな型から小さなサブセットが欲しい場合はPickを使用(インクルードリスト)
- 少数を除いたほとんどのプロパティが欲しい場合はOmitを使用(エクスクルードリスト)
// これらは同じ結果を生成:
type A = Pick<User, "id" | "name">;
type B = Omit<User, "email" | "password" | "avatar" | "createdAt">;
ユースケース
Pick<T, K>はDTO(Data Transfer Object)の作成、APIレスポンスの整形、より大きなモデルの一部のフィールドだけを使用するコンポーネントpropsの定義、データの読み取り専用ビューの構築に使用します。