Record<Keys, Value> tạo object type với specific keys và value type.
- Khác index signature: Keys có thể là specific union (yêu cầu tất cả keys có mặt, không optional).
- Rõ ràng hơn và type-safe hơn index signature.
typescript
const routes: Record<'home' | 'about' | 'contact', string> = {
home: '/',
about: '/about',
contact: '/contact', // thiếu key này → Error
};
// Dùng với string key rộng hơn:
const cache: Record<string, unknown> = {};Record<Keys, Value> creates an object type with specific keys and a value type.
- Unlike index signatures: Keys can be a specific union (all keys must be present, none optional).
- Clearer and more type-safe than an index signature.
typescript
const routes: Record<'home' | 'about' | 'contact', string> = {
home: '/',
about: '/about',
contact: '/contact', // missing this key → Error
};
// Wider string key:
const cache: Record<string, unknown> = {};