はじめに
TypeScriptのユーティリティ型は種類が多いですが、実務で頻繁に使うものは限られています。今回は特に実用的なものを厳選して紹介します。
Pick / Omit
オブジェクト型から特定のプロパティを選択・除外します。
interface User {
id: number;
name: string;
email: string;
password: string;
}
// APIレスポンス用(passwordを除外)
type UserResponse = Omit<User, 'password'>;
// 更新用(nameとemailだけ)
type UserUpdate = Pick<User, 'name' | 'email'>;
Partial / Required
全プロパティをオプショナル / 必須にします。
// 部分更新に便利
function updateUser(id: number, data: Partial<User>) {
// data.name, data.email は undefined の可能性がある
}
Record
キーと値の型を指定してオブジェクト型を作ります。
type Status = 'pending' | 'active' | 'archived';
type StatusConfig = Record<Status, { label: string; color: string }>;
const config: StatusConfig = {
pending: { label: '保留中', color: 'yellow' },
active: { label: '有効', color: 'green' },
archived: { label: 'アーカイブ', color: 'gray' },
};
Extract / Exclude
ユニオン型のフィルタリングに使います。
type Event = 'click' | 'scroll' | 'mousemove' | 'keydown' | 'keyup';
// マウス系イベントだけ
type MouseEvent = Extract<Event, 'click' | 'scroll' | 'mousemove'>;
// キーボード系以外
type NonKeyEvent = Exclude<Event, 'keydown' | 'keyup'>;
まとめ
これらを使いこなすと、型定義の重複を大幅に減らせます。特に Pick / Omit と Partial は毎日のように使う場面があるので覚えておくと便利です。