Understanding Index Signatures in TypeScript
Hemanta Sundaray
Published December 25, 2023
An index signature in TypeScript is used to specify that an object, when defined by a certain interface, can have any number of properties with a certain key type and corresponding value type. This is especially useful in scenarios where you don't know the exact property names beforehand but do know the type of the keys and values.
Index Signature Syntax
The syntax of an index signature is as follows:
[key: T] : U
- [key: T]: This part of the syntax defines the 'shape' of the keys in the object. The word key is just a placeholder; you can use any word here. T represents the type of the keys.
- :U: This part defines the type of the values that correspond to the keys in the object.
Note
Index signatures are most commonly used with string keys. This is due to how JavaScript handles object properties. In JavaScript, keys of an object are always strings (or Symbols, but that's a less common case). Even if you use a number or another type as a key, JavaScript implicitly converts it to a string.
Index Signature Example
interface UserProfiles {
[username: string]: { age: number; email: string };
}
const profiles: UserProfiles = {};
profiles["johnDoe"] = { age: 30, email: "john@example.com" };
profiles["janeDoe"] = { age: 25, email: "jane@example.com" };
In this example, the UserProfiles interface uses an index signature, allowing you to add any number of user profiles with string keys.