TypeScriptのRecordを解説

typescript

本記事では、TypeScriptのユーティリティ型のひとつであるRecordについて解説します。

Recordを使用することで、入れ子になっているオブジェクト型の定義を簡潔に記述できます。

Record<Keys, Type>

Recordはkeysをプロパティのkeyに、Typeをプロパティのvalueとした型を作ります。

keysに代入可能な型は、stringnumbersymbolとそれぞれのリテラル型です。

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のようにリテラル型をキーに指定できないことです。

タイトルとURLをコピーしました