Record<K, T>: Creating Uniform Object Types
What you'll learn: How Record<K, T> maps a union of keys to a consistent value type for dictionary-like objects.
The Core Idea
Record<K, T> is a utility type that creates an object type where every key from the union K must have a value of type T. Think of it as a template for creating uniform dictionaries: "I want an object where these specific keys all point to the same kind of value."
The syntax looks like this:
type MyDictionary = Record<'name' | 'email', string>;
// Same as: { name: string; email: string }
Why This Matters
Instead of manually typing out each property, Record generates them for you. This is especially useful when your keys come from string literal unions or other computed types:
type Role = 'admin' | 'user' | 'guest';
type Permissions = Record<Role, boolean>;
// Result: { admin: boolean; user: boolean; guest: boolean }
const access: Permissions = {
admin: true,
user: true,
guest: false
};
Dictionary Pattern
Record shines when creating lookup tables or configuration objects:
type HttpMethod = 'GET' | 'POST' | 'PUT';
type RouteConfig = Record<HttpMethod, string>;
const routes: RouteConfig = {
GET: '/items',
POST: '/items',
PUT: '/items'
};
You can also use string or number as the key type for truly flexible dictionaries:
type UserMap = Record<string, number>;
const ages: UserMap = {
alice: 30,
bob: 25
};
Key Takeaway: Record<K, T> creates object types where all keys from union K must have values of type T, perfect for uniform dictionaries and lookup tables.