TypeScript Index Signatures
🔑 TypeScript Index Signatures (Beginner → Advanced)
Index Signatures in TypeScript let you describe the shape of objects with dynamic (unknown) property names.
They are essential when working with maps, dictionaries, API responses, configs, and dynamic keys.
1️⃣ What Is an Index Signature?
An index signature defines the type of values for properties when the property names are not known in advance.
✔ Any string key
✔ Value must be a string
2️⃣ Basic Index Signature Example ⭐
✔ Common for form validation errors
3️⃣ Index Signature with number Keys ⭐
📌 In JavaScript, number keys are converted to strings, but TS treats them separately for typing.
4️⃣ Mixing Known Properties with Index Signatures ⚠️
When you add explicit properties, their types must be compatible with the index signature.
✔ All properties must match the index signature value type
5️⃣ Readonly Index Signatures 🔒
✔ Prevents mutation
6️⃣ Optional vs Index Signature ❓
👆 This is not an index signature.
Index signature allows any key:
7️⃣ Index Signatures vs Record ⭐⭐
Index Signature
Record (Preferred Often)
✔ Record is safer when keys are known
✔ Index signatures when keys are truly dynamic
8️⃣ Index Signatures with Union Value Types ⭐
✔ Very common in configuration objects
9️⃣ Index Signatures + Mapped Types 🔥
✔ Strongly typed keys
✔ Safer than raw index signatures
🔟 Index Signatures with unknown (Safer) ⭐
✔ Forces type narrowing
✔ Better than any
1️⃣1️⃣ Common Mistakes ❌
Using index signatures when keys are known
Forgetting that all properties must match the value type
Using
anyinstead ofunknownOverusing index signatures instead of
RecordExpecting number index signatures to differ at runtime
📌 Interview Questions (Must Prepare)
What is an index signature?
Difference between index signature and
Record?Can we mix fixed properties with index signatures?
Why must property types match the index signature?
stringvsnumberindex signatures?When should index signatures be avoided?
🔥 Real-World Use Cases
API response objects with dynamic keys
Localization dictionaries
Feature flags
Form validation errors
Caching & lookup tables
✅ Summary
✔ Index signatures handle dynamic object keys
✔ Syntax: [key: string]: ValueType
✔ All properties must match the value type
✔ Prefer Record when keys are known
✔ Use unknown for safety
✔ Essential for real-world TypeScript & interviews
