読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
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<string, Product> のように K を string にすると、どんな名前でも読めてしまいます。設定によっては、ない名前を読んでも Product 型になるため、②で確かめた noUncheckedIndexedAccess を有効にして、undefined の可能性を残します。
type BadgeColor = "green" | "gray" | "red"; を作り、const statusColors: Record<ReservationStatus, BadgeColor> = { reserved: "green", picked_up: "gray", cancelled: "red" }; と書きます。
7 / 16