The Record
Utility Type in TypeScript
TypeScript provides a rich set of utility types to help developers write cleaner and more robust code. One of the most useful and versatile is the Record
type. In this article, I'll explore what Record
is, when to use it, and how to use it effectively with real-world examples.
What is Record
?
The Record
type is TypeScript utility type that lets you define an object type with a specific set of keys and a consistent value type for all keys.
Syntax
Record<Keys, ValueType>
- Keys: The union of keys you want the object to have (must be a type that extends
string
|number
|symbol
). - ValueType: The type of the values associated with those keys.
Example
type UserRole = 'admin' | 'user' | 'guest';
const rolePermissions: Record<UserRole, string[]> = {
admin: ['read', 'write', 'delete'],
user: ['read', 'write'],
guest: ['read']
};
enum Status {
New = 'new',
InProgress = 'in_progress',
Done = 'done'
}
const statusLabels: Record<Status, string> = {
[Status.New]: 'New Task',
[Status.InProgress]: 'Task In Progress',
[Status.Done]: 'Completed Task'
};
type CountryCode = 'US' | 'JP' | 'FR';
const countryNames: Record<CountryCode, string> = {
US: 'United States',
JP: 'Japan',
FR: 'France'
};
type Lang = 'en' | 'ja';
type Page = 'home' | 'about';
const translations: Record<Lang, Record<Page, string>> = {
en: {
home: 'Home',
about: 'About Us'
},
ja: {
home: 'ホーム',
about: '私たちについて'
}
};
type Product = {
name: string;
price: number;
};
type ProductID = 'p1' | 'p2';
const productCatalog: Record<ProductID, Product> = {
p1: { name: 'Keyboard', price: 99 },
p2: { name: 'Mouse', price: 49 }
};
type Features = 'darkMode' | 'betaAccess';
const featureFlags: Partial<Record<Features, boolean>> = {
darkMode: true
};
Top comments (0)