🙄
[Typescript]よく使うユーティリティ型
TypeScript ユーティリティ型まとめ
1. keyof
keyofを使用すると、インターフェースのキーをユニオン型として取得できます。
interface User {
id: number;
name: string;
age: number;
gender: "m" | "f";
}
type UserKey = keyof User; // 'id' | 'name' | 'age' | 'gender';
const userKey1: UserKey = 'phone'; // エラー
const userKey2: UserKey = 'id'; // OK
2. Partial<T>
Partial<T>は、すべてのプロパティをオプショナル(任意)にします。そのため、一部のプロパティだけを使用することが可能です。
interface User {
id: number;
name: string;
age: number;
gender: "m" | "f";
}
const admin1: User = { // ageやgenderがないとエラーになる
id: 1,
name: "bob"
};
const admin2: Partial<User> = { // エラーが発生しない
id: 1,
name: "bob"
};
// Partial<User>は以下のような形になる
// interface User {
// id?: number;
// name?: string;
// age?: number;
// gender?: 'm' | 'f';
// }
3. Required<T>
Required<T>は、すべてのプロパティを必須にします。オプショナルプロパティも必須となります。
interface User {
id: number;
name: string;
age: number;
gender?: 'm' | 'f'; // オプショナル
}
const admin1: User = { // エラーは発生しない
id: 1,
name: "bob",
age: 20
};
const admin2: Required<User> = { // genderを入力しないとエラーが発生
id: 1,
name: "bob",
age: 20,
gender: "m"
};
さらに便利なユーティリティ型について追記予定
4. Readonly<T>
Readonly<T>はプロパティを最初の代入時のみ許可し、その後の変更を禁止します。
interface User {
id: number;
name: string;
}
const admin: Readonly<User> = {
id: 1,
name: "bob"
}
admin.id = 2; // エラー: 読み取り専用プロパティに代入できません
5. Record<K, T>
Record<K, T>は、キーKと値Tを持つオブジェクト型を作成します。
例1: 手動で型定義した場合
interface Score {
"1": "A" | "B" | "C" | "D";
"2": "A" | "B" | "C" | "D";
"3": "A" | "B" | "C" | "D";
"4": "A" | "B" | "C" | "D";
}
const score:Score = {
1: "A",
2: "B",
3: "C",
4: "D"
}
例2: Record<K, T>を使用して簡略化
//ステップ1: キーと型を直接指定する
const score1:Record<"1" | "2" | "3" | "4", "A" | "B" | "C" | "D"> = {
1: "A",
2: "B",
3: "C",
4: "D"
}
//ステップ2: 型を分離してさらに簡潔にする
type Grade = "1" | "2" | "3" | "4";
type Score = "A" | "B" | "C" | "D";
const score2: Record<Grade, Score> = {
1: "A",
2: "B",
3: "C",
4: "D"
}
6. Pick<T,K>
指定したプロパティだけを抜き出して新しい型を作成します。Tタイプから、Kプロパティを選んで使います。
interface User {
id:number;
name:string;
age:number;
gender: "f" | "m"
}
const admin: Pick<User, "id" | "name"> = {
id: 1,
name: "bob"
}
7. Omit<T,K>
指定したプロパティを除外して新しい型を作成します。
interface User {
id:number;
name:string;
age:number;
gender: "f" | "m"
}
const admin: Omit<User, "age" | "gender"> = {
id: 1,
name: "bob"
}
7. Exclude<T1,T2>
T1の型の中からT2の型と重複するものを除外します。Omit<T, K>はプロパティを削除するのに対し、Exclude<T1, T2>は型そのものを削除します。
type T1 = string | number | boolean;
type T2 = Exclude<T1, number | string>; // booleanだけ残る
8. NonNullable<Type>
nullとundefinedを除外します。
type T1 = string | null | undefined | void
type T2 = NonNullable<T1> // stringとvoidだけ残る
参考文献
Discussion