← Back to TypeScript Course | Chapter 8: Advanced Types | Lesson 15 of 20

Utility Types - Record

Record<K, T> creates an object type whose keys come from K and whose values all have type T. It is useful for dictionaries and lookup tables.

Basic Record

Record<K, T> creates an object type whose keys come from K and whose values are all of type T, which is useful for describing dictionaries or lookup tables with a known key type.

Example: Basic Record

typescript
type Inventory = Record<string, number>;
const stock: Inventory = { apples: 10, bananas: 5 };
console.log(stock);

Record with Number Values

Record is useful for maps where every known key stores a numeric value, such as Record<small | medium | large, number> for describing sizes and their corresponding prices.

Example: Record with Number Values

typescript
type SizePrices = Record<"small" | "medium" | "large", number>;
const prices: SizePrices = { small: 5, medium: 7, large: 9 };
console.log(prices.medium);

Record with Object Values

The value type T in Record can itself be an object type, letting you describe more complex lookup structures such as a map of user IDs to full user objects. This makes Record just as useful for structured caches as it is for simple dictionaries.

Example: Record with Object Values

typescript
interface User {
  id: number;
  name: string;
}
type UserMap = Record<number, User>;
const users: UserMap = { 1: { id: 1, name: "Ravi" } };
console.log(users[1].name);

Record with Dynamic Keys

Record can use string or number as a general key type when the exact set of keys isn't known ahead of time, effectively describing an open-ended dictionary rather than a fixed set of named fields.

Example: Record with Dynamic Keys

typescript
type Scores = Record<string, number>;
const scores: Scores = {};
scores["alice"] = 90;
scores["bob"] = 85;
console.log(scores);

When to Use Record

Use Record for dictionaries, lookup tables, configuration maps, and any other fixed-key collection where every value should share the same type. It's often a cleaner alternative to an index signature when the value type is consistent across every key.

Example: When to Use Record

typescript
type PlanPrices = Record<"free" | "pro" | "enterprise", number>;
const prices: PlanPrices = { free: 0, pro: 20, enterprise: 100 };
console.log(prices);

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.