0
0
Typescriptprogramming~3 mins

Why Index signatures for dynamic keys in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your code could handle any property without breaking or rewriting?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
const user = { name: 'Alice', age: 30 };
console.log(user.name);
console.log(user.age);
// What if user has more properties?
After
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 dynamically
What It Enables

It enables flexible and safe access to object properties when keys are not fixed or known in advance.

Real Life Example

Think of a settings panel where users can add custom options. Index signatures let your code handle any new option without extra changes.

Key Takeaways

Manual property handling is slow and error-prone.

Index signatures allow dynamic keys safely.

This makes your code flexible and easier to maintain.