TypeScript Index Signatures
TypeScript index signatures are a versatile feature that lets you define objects with dynamically named properties. They are like a Swiss Army knife for creating flexible data structures. With index signatures, you can specify both the type of keys and the type of their values within an object, enabling you to create dictionaries, configuration objects, and other dynamic data structures. By understanding index signatures, you can write more efficient and maintainable code.
Introduction to Index Signatures
Index signatures in TypeScript help define objects with properties that don't have predefined names but have known types. For example:
interface StringDictionary {
[key: string]: string;
}
const myDict: StringDictionary = {
hello: "world",
goodbye: "everyone"
};
In this example, any string can be used as a key, and each value must be a string. This pattern is common when working with configuration objects, API responses, or user-generated data.
Syntax of Index Signatures
The syntax for index signatures is straightforward: you specify the key type in square brackets followed by the value type. This defines how you can access properties by keys. For example:
interface NumberMap {
[index: number]: number;
}
const numMap: NumberMap = {
0: 1,
1: 2,
2: 3
};
Here, we use number keys, which is useful for array-like objects. The key type can be string
, number
, or symbol
, but string
is most common.
Basic Usage of Index Signatures
Index signatures are useful when you don't know all property names in advance but know their types. They are perfect for managing collections of similar items. For example:
interface UserAges {
[name: string]: number;
}
const ages: UserAges = {
Alice: 30,
Bob: 25
};
// You can add new properties dynamically
ages.Charlie = 28;
This pattern works well for caching data, managing dynamic configurations, or handling API responses with variable keys.