TypeScript ยท Chapter 31 of 44

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.

Syntax
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.

Example 1 (typescript)
type Scores = Record<string, number>;
const scores: Scores = { Alice: 90, Bob: 85 };
console.log(scores.Alice);
Output
90

Scores describes an object where any string key maps to a number value.

Example 2 (typescript)
type Colors = Record<"red" | "green" | "blue", string>;
const hex: Colors = { red: "#f00", green: "#0f0", blue: "#00f" };
console.log(hex.green);
Output
#0f0

Colors 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.
๐Ÿ’ก Note: Record is one of the most practical utility types for working with structured lookup data.

๐Ÿ“ Quick Quiz

1. What does Record<string, number> describe?

2. What happens if a Record with literal keys is missing a required key?

3. Record is most useful for describing: