Trung BìnhTypeScript iconTypeScript

Index signature trong TypeScript là gì?

Index signature cho phép object có keys không biết trước.

Tất cả explicit properties phải compatible với index signature type.

typescript
interface StringMap { [key: string]: string }
const headers: StringMap = { 'Content-Type': 'application/json' };

// Lưu ý: explicit properties cũng phải match
interface WithLength {
  [key: string]: string;
  length: number; // Error! length phải là string
}

// Record<K,V> thường rõ ràng hơn:
const routes: Record<string, string> = { home: '/', about: '/about' };

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

Mở danh sách TypeScript