読み方のヒント

矢印ボタン(または ← → キー)でページを移動できます。

第2節 Partial・Required・Readonly・Record

2.2 Record

Record<K, V> は、名前が K、値が V のオブジェクトの型です。

type ProductCategory = "bread" | "pastry" | "savory" | "sweets";

const categoryLabels: Record<ProductCategory, string> = {
  bread: "食事パン",
  pastry: "菓子パン",
  savory: "総菜パン",
  sweets: "菓子",
};

K にリテラル型のユニオンを渡すと、すべての名前がそろっていることが求められます。sweets を書き忘れると、エラーになります。

Property 'sweets' is missing in type '{ bread: string; pastry: string; savory: string; }' but required in type 'Record<ProductCategory, string>'.
K に渡す型意味
リテラル型のユニオン決まった名前がすべてそろったオブジェクト
stringどんな名前でもよいオブジェクト(辞書)

Record&lt;string, Product&gt; のように K を string にすると、どんな名前でも読めてしまいます。設定によっては、ない名前を読んでも Product 型になるため、②で確かめた noUncheckedIndexedAccess を有効にして、undefined の可能性を残します。

解答の例

type BadgeColor = "green" | "gray" | "red"; を作り、const statusColors: Record&lt;ReservationStatus, BadgeColor&gt; = { reserved: "green", picked_up: "gray", cancelled: "red" }; と書きます。

7 / 16