Sub topic 1
Objects Used as Dictionaries
Prerequisites
This chapter assumes basic TypeScript types, interfaces, type aliases, union types, and undefined. You should also know JavaScript object property access with dot and bracket notation.
Objects Used as Dictionaries
A dictionary object stores values under keys that are not all known when you write the program. For example, a score table might receive a new player's name at runtime:
const scores = {
alice: 90,
bob: 85,
};
scores["carol"] = 92;Without an explicit type, TypeScript usually infers only the properties present in the initial value. An index signature describes the type of values for unknown keys.
Declaring an Index Signature
The syntax uses a key name, a key type, and a value type:
const scores: { [name: string]: number } = {};
scores["alice"] = 90;
scores.bob = 85;
// scores.carol = "A"; // Error: string is not assignable to number[name: string]: number means that every string key must have a numeric value. The name name is only a label. You could write [key: string] instead.
You can also declare an index signature in an interface:
interface Scores {
[player: string]: number;
}
const scores: Scores = { alice: 90 };An index signature permits both bracket notation and dot notation when the property name is a valid identifier.
Which Key Types Are Allowed
Index signatures support string, number, and symbol keys:
interface StringValues {
[key: string]: string;
}
interface NumberValues {
[key: number]: string;
}
interface SymbolValues {
[key: symbol]: string;
}Use a string index signature for names, IDs, or other text keys. Use a number index signature for numeric indexing, such as array-like structures. Use a symbol index signature when symbol keys are part of the design.
A JavaScript object converts numeric property keys to strings at runtime. TypeScript still lets you describe numeric access separately, but a string index signature must be broad enough to include values reached through numeric keys.
Mixing Known Properties with an Index Signature
Every named property must be assignable to the index signature's value type:
interface Config {
[key: string]: string | number;
name: string;
retries: number;
}
const config: Config = {
name: "worker",
retries: 3,
region: "us-east-1",
};The union string | number is necessary because both name and retries are known properties with different types.
Exercise
Why does interface Bad { [key: string]: string; retries: number } produce an error?
Show answer
retries is a string-keyed property, but its value is a number. It is not assignable to the string index signature.