Sub topic 6
Index signatures for dictionary-like objects
Assume you know basic TypeScript annotations and JavaScript objects. This chapter focuses on objects whose property names are not known when you write the code.
An index signature describes the type of values accessed through dynamic keys. A dynamic key is a property name stored in a variable or received from outside the program.
interface Scores {
[playerName: string]: number;
}
const scores: Scores = {
Ada: 10,
Grace: 12,
};
const name = "Ada";
console.log(scores[name]); // 10[playerName: string] means that every string key must produce a number. The name playerName is only documentation. It does not restrict the actual property names.
Reading and writing dynamic properties
An index signature supports normal property access and bracket access.
interface Inventory {
[sku: string]: number;
}
const stock: Inventory = {};
stock["book-101"] = 8;
stock["pen-202"] = 25;
function quantity(sku: string, inventory: Inventory): number {
return inventory[sku];
}
console.log(quantity("book-101", stock)); // 8The compiler checks the value type on assignment. This assignment is an error because "many" is not a number:
// stock["book-101"] = "many";An index signature does not guarantee that a requested key exists at runtime. If the key is absent, JavaScript returns undefined.
With the noUncheckedIndexedAccess compiler option enabled, TypeScript includes undefined in indexed reads. Code must then handle a missing entry:
interface Prices {
[product: string]: number;
}
function getPrice(product: string, prices: Prices): number {
const price = prices[product];
if (price === undefined) {
return 0;
}
return price;
}This option catches a common error: treating every lookup as if it were successful.
Known properties and index signatures
An object type can combine named properties with an index signature. Every named property must be compatible with the index signature's value type.
interface Headers {
[headerName: string]: string;
contentType: string;
requestId?: string;
}
const headers: Headers = {
contentType: "application/json",
requestId: "abc-123",
};Both named properties are strings, so they satisfy the index signature. This would be invalid:
// interface InvalidHeaders {
// [headerName: string]: string;
// retryCount: number; // error: number is not assignable to string
// }Use a wider value type when the dictionary and named properties genuinely contain different kinds of values:
interface Settings {
[key: string]: string | number;
retries: number;
region: string;
}Avoid using any merely to silence this compatibility check. A union keeps the possible values visible to callers.
String and number indexes
A number index signature describes array-like access:
interface Labels {
[index: number]: string;
}
const labels: Labels = ["low", "medium", "high"];
console.log(labels[1]); // mediumAn interface may have both string and number index signatures, but the number value type must be assignable to the string value type. JavaScript converts numeric property names to strings, so a numeric lookup must remain compatible.
| Need | Common type |
|---|---|
| Arbitrary string keys | `{ [key: string]: Value }` |
| Numeric positions | `{ [index: number]: Value }` |
| Fixed set of known keys | An interface or object type |
Exercise
What is wrong with interface Counts { [key: string]: number; total: string; }, and how could you correct it?
Show answer
total must be assignable to the string index value type, but string is not assignable to number. Change total to number, or widen the index signature to number | string if both value types are intentional.