Index signatures allow you to define types for objects where property names are not known in advance, but the property key types and value types conform to a consistent rule.
// Key must be string, number, or symbol
interface DynamicDictionary {
[key: string]: string | number;
}
// Index signature for dynamic API cache
interface ApiCache {
[endpoint: string]: {
data: unknown;
timestamp: number;
};
}
const cache: ApiCache = {};
cache["/api/v1/users"] = {
data: [{ id: 1, name: "Alice" }],
timestamp: Date.now()
};
cache["/api/v1/settings"] = {
data: { theme: "dark" },
timestamp: Date.now()
};
// Combining Index Signatures with Explicit Properties
interface UserMap {
readonly systemOwner: string; // Explicit property
[userId: string]: string; // Index signature
}
const team: UserMap = {
systemOwner: "admin_01",
usr_100: "Bob",
usr_200: "Charlie"
};
console.log(`Cache Entries: ${Object.keys(cache).length} | Owner: ${team.systemOwner}`);
Record<K, V> as a Cleaner Alternative: Record<string, User> is often more readable than [key: string]: User.[key: string]: number, all named properties in that interface must also be of type number.noUncheckedIndexedAccess: Prevents runtime bugs by typing dictionary[key] as T | undefined instead of assuming T exists.Define an index signature type StringArrayMap where keys are string and values are arrays of strings (string[]).
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With