TypeScript Record Type
The `Record<Keys, Type>` utility type creates an object type where every key from `Keys` maps to a value of `Type`. It's a convenient way to describe dictionaries or lookup tables.
Record is often used together with a union of string literals as the key type, ensuring the resulting object must have exactly those keys, no more and no less.
type Scores = Record<string, number>;
type Colors = Record<"red" | "green" | "blue", string>;Basic Record usage
`Record<string, number>` describes an object where every key is a string and every value is a number, similar to a simple dictionary.
Record with literal keys
`Record<"red" | "green" | "blue", string>` requires an object to have exactly the keys red, green, and blue, each mapped to a string value.
type Scores = Record<string, number>;
const scores: Scores = { Alice: 90, Bob: 85 };
console.log(scores.Alice);90Scores describes an object where any string key maps to a number value.
type Colors = Record<"red" | "green" | "blue", string>;
const hex: Colors = { red: "#f00", green: "#0f0", blue: "#00f" };
console.log(hex.green);#0f0Colors requires exactly the keys red, green, and blue, each with a string value.
Key points
- Record<Keys, Type> builds an object type mapping keys to a value type.
- It is great for describing dictionaries and lookup tables.
- Combined with literal key unions, it enforces an exact set of required keys.
- Missing a required key in a literal-based Record causes a compile error.
