๐ŸŽ“ A1Learner
๐Ÿ”
0 of 42 lessons completed

TypeScript Record in Depth

Record<Keys, Value> builds an object type from a union of keys and one value type. Every key in the union must appear in the value.

A complete table for every status

The key union has three statuses. The Record value supplies a label for each one.

type CartStatus = "open" | "paid" | "shipped";
const labels: Record<CartStatus, string> = {
  open: "Open",
  paid: "Paid",
  shipped: "Shipped",
};
console.log(labels.open);
console.log(labels.paid);
console.log(labels.shipped);

A missing key is refused

This table leaves out the shipped status. The checker refuses the value before it can run.

type CartStatus = "open" | "paid" | "shipped";
const labels: Record<CartStatus, string> = {
  open: "Open",
  paid: "Paid",
};
console.log(labels.open);

A lookup table replaces a switch

Each status maps to a handler function. Calling through the table runs the handler for that status.

type CartStatus = "open" | "paid" | "shipped";
const handlers: Record<CartStatus, () => string> = {
  open: () => "Cart is open",
  paid: () => "Payment received",
  shipped: () => "Parcel shipped",
};
console.log(handlers.open());
console.log(handlers.shipped());

Example

type OrderPhase = "placed" | "packed" | "delivered";
const messages: Record<OrderPhase, string> = {
  placed: "Order placed",
  packed: "Order packed",
  delivered: "Order delivered",
};
function messageFor(phase: OrderPhase): string {
  return messages[phase];
}
console.log(messageFor("packed"));
console.log(messageFor("delivered"));

Key points

  • Record forces every key of a key union to exist in the value.
  • A missing key is a compile error, not a runtime surprise.
  • A Record table can replace a switch by holding one handler per key.
  • Record<string, T> types a plain dictionary that accepts any string key.

In this example, a Record table holds one message per order phase, and messageFor reads the entry for the phase it is given.

Note

The key union fixes the table shape, so new keys need a type change first.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท TypeScript Playground

Exercise

A Record<CartStatus, string> value is missing the shipped key. What does the checker do?