Utility Types - Record
In this page:
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
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
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
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
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
type PlanPrices = Record<"free" | "pro" | "enterprise", number>;
const prices: PlanPrices = { free: 0, pro: 20, enterprise: 100 };
console.log(prices);
Chapter Quiz — Complete all 20 topics to unlock
0/20 topics done
Complete these topics first:
- TypeScript Advanced Types
- Mapped Types
- Conditional Types
- Custom Type Guards
- Assertion Functions
- Control Flow Analysis
- Exhaustiveness Checking
- Satisfies Operator
- Template Literal Types
- Utility Types - Partial
- Utility Types - Required
- Utility Types - Readonly
- Utility Types - Pick
- Utility Types - Omit
- Utility Types - Record
- Utility Types - Exclude and Extract
- Utility Types - NonNullable
- Utility Types - ReturnType
- Utility Types - Parameters
- TypeScript 5 Updates