本記事では、TypeScriptのユーティリティ型のひとつであるRecord
について解説します。
Record
を使用することで、入れ子になっているオブジェクト型の定義を簡潔に記述できます。
Record<Keys, Type>
Recordはkeysをプロパティのkeyに、Typeをプロパティのvalueとした型を作ります。
keysに代入可能な型は、string
、number
、symbol
とそれぞれのリテラル型です。
type User = Record<'name' | 'email', string>;
/*
以下と同じです。
type User = {
name: string,
email: string
}
*/
const user: User = {
name: 'John Doe',
email: 'john@example.com'
};
Type
には複雑な型を使用することもできます。
type User = {
age: number,
name: string
}
type Users = Record<'taro' | 'hanako', User>;
/*
以下と同じです。
type Users = {
taro: {
age: number,
name: string
},
hanako: {
age: number,
name: string
}
}
*/
const users: Users = {
taro: { age: 25, name: '田中太郎' },
hanako: { age: 22, name: '山田花子' }
};
インデックス型との違い
Record
と似たようなことはインデックス型でもできます。インデックス型はプロパティ名を指定せずに型のみを指定します。
// 数値のインデックス型
type NumberDict = { [key: string]: number };
const scores: NumberDict = {
math: 90,
science: 85,
english: 92
};
また、以下のRecord
とインデックス型は同じです。
type RecordType = Record<string, number>;
type IndexType = {[K: string], number};
主な違いは、インデックス型ではRecord
のようにリテラル型をキーに指定できないことです。