What if your code could handle any property without breaking or rewriting?
Why Index signatures for dynamic keys in Typescript? - Purpose & Use Cases
Imagine you have a list of users, and each user can have different properties like age, name, or email. You try to write code that accesses these properties one by one, but you don't know all the property names in advance.
Manually writing code for each possible property is slow and messy. If a new property appears, you must change your code everywhere. This leads to mistakes and makes your program hard to maintain.
Index signatures let you tell TypeScript: "I don't know all the property names, but they will follow a pattern." This way, you can safely access any property dynamically without errors or rewriting code.
const user = { name: 'Alice', age: 30 };
console.log(user.name);
console.log(user.age);
// What if user has more properties?interface User {
[key: string]: string | number;
}
const user: User = { name: 'Alice', age: 30 };
console.log(user['name']);
console.log(user['age']);
// Works for any property dynamicallyIt enables flexible and safe access to object properties when keys are not fixed or known in advance.
Think of a settings panel where users can add custom options. Index signatures let your code handle any new option without extra changes.
Manual property handling is slow and error-prone.
Index signatures allow dynamic keys safely.
This makes your code flexible and easier to maintain.