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' };An index signature allows objects to have unknown keys in advance.
All explicit properties must be compatible with the index signature type.
typescript
interface StringMap { [key: string]: string }
const headers: StringMap = { 'Content-Type': 'application/json' };
// Note: explicit properties must also match the index signature type
interface WithLength {
[key: string]: string;
length: number; // Error! length must also be string
}
// Record<K,V> is often clearer:
const routes: Record<string, string> = { home: '/', about: '/about' };