Cơ BảnTypeScript iconTypeScript

`Record<K, V>` là gì? Khác index signature như thế nào?

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> = {};

Xem toàn bộ TypeScript cùng filter theo level & chủ đề con.

Mở danh sách TypeScript