Sometimes, you do not know the exact names of the properties an object will contain.
However, you do know the exact shape or type those hidden properties should take.
Index signatures allow you to strongly type objects with completely dynamic keys.
They are heavily used when building dictionaries, caches, or parsing dynamic JSON data.
An index signature is defined using square brackets inside an interface or type.
You specify the type of the key (usually string or number) and the type of the value.
This tells TypeScript: "Any property added to this object must match these specific types."
It provides dynamic flexibility without sacrificing any underlying type security.
interface ErrorCache {
// Any string key must resolve to a string message
[errorCode: string]: string;
}
const errors: ErrorCache = {};
errors["404"] = "Page not found";
errors["500"] = "Internal Server Error";
// errors["403"] = 403; // Error: Must be a string value
console.log(errors["404"]);
You can mix explicitly named properties with an index signature in the same interface.
However, all explicitly named properties must strictly match the index signature's value type.
If the signature expects strings, a hardcoded property cannot suddenly be a boolean.
This enforces uniformity across the entire data structure seamlessly.
interface UserMap {
[userId: string]: string;
adminName: string; // Valid, it matches the signature!
// age: number; // Error: Property 'age' of type 'number' is not assignable to string index type
}
let users: UserMap = { adminName: "Akash" };
users["user_1"] = "John";
console.log(users.adminName);
Index signatures are perfect for building memory-efficient caching systems in the frontend.
Caching API data locally significantly reduces server requests and latency metrics.
A fast, snappy website immediately benefits from improved SEO indexing speeds.
Properly typing these caches guarantees your rendered UI will never crash unexpectedly.
interface ProductList {
[productId: number]: string;
}
const list: ProductList = {
101: "Laptop",
102: "Mouse"
};
console.log("Product:", list[101]);
Which syntax is used to define an index signature for dynamic string keys?
Index signatures are incredible tools for mapping unpredictable external data safely.
Use them whenever you need a dynamic dictionary or lookup table.
Next, we'll explore the automatic magic of Declaration Merging!