TypeScript
/Intermediate
Index Signatures
Definition
A way to type an object when you don't know the exact names of the object's properties ahead of time, but you do know the shape of the values.
Explain Like I'm New
Imagine an English dictionary. You don't know exactly what words are going to be in the book, but you know that every single word (the Key) will be a String, and every definition (the Value) will also be a String. An Index Signature is how you tell TypeScript this rule.
Real World Example
Typing a translation JSON file where the keys are dynamic language codes ('en', 'es', 'fr') and the values are the translation strings.
Common Use Cases
- •Dictionaries / Hash Maps
- •Dynamic CSS modules
- •Environment variables
Interactive Example
// We don't know the keys, but we know all values are numbers interface SalaryDictionary { [employeeName: string]: number; } const salaries: SalaryDictionary = { alice: 100000, bob: 95000, charlie: 105000 }; // ERROR: Type 'string' is not assignable to type 'number'. // salaries.dave = "High"; // Mixing known properties (They must match the index type) interface FlexibleDict { id: string; [key: string]: string; // Because of this, 'id' MUST be a string }
Interview Questions
basic
- What is the syntax for an Index Signature?
intermediate
- Can you mix known properties with an index signature?
advanced
- Can the key of an index signature be a boolean?