Sub topic 1
Objects Used as Dictionaries
A JavaScript object can represent a fixed-shaped record or a dictionary. A fixed-shaped record has a known set of properties, such as a user with id and email. A dictionary has keys that are discovered at runtime. For example, a word counter might store one entry for every word found in a document.
TypeScript needs different information for these two cases. With a fixed record, you describe each property by name. With a dictionary, you describe the type of value associated with each possible key.
Prerequisites
This chapter assumes that you understand basic TypeScript types, interfaces, type aliases, union types, and undefined. You should also know JavaScript object property access with dot notation and bracket notation.
The dictionary problem
Consider this JavaScript code:
const scores = {};
scores["alice"] = 90;
scores["bob"] = 85;
scores["carol"] = 92;
console.log(scores["alice"]);The keys are names, and the values are numbers. The program can add another name without changing a class or interface declaration.
The empty object does not communicate this rule clearly to TypeScript. A useful dictionary type needs to answer two questions:
- What kinds of keys are allowed?
- What type does each value have?
For this example, the intended rule is “any string key maps to a number.” An index signature expresses that rule. An index signature is a type declaration for properties whose names are not known in advance.
Dot notation and bracket notation
When the key is a fixed identifier, dot notation is convenient:
const prices = {
coffee: 3.5,
tea: 2.75,
};
console.log(prices.coffee);When the key is stored in a variable, use bracket notation:
const item = "tea";
console.log(prices[item]);Dictionary access usually uses bracket notation because the key often comes from input, a loop, a file, or another data source.
const quantities: { [product: string]: number } = {};
for (const product of ["coffee", "tea", "coffee"]) {
quantities[product] = (quantities[product] ?? 0) + 1;
}
console.log(quantities["coffee"]); // 2The variable name inside an index signature, product in this example, is documentation. It does not restrict the actual keys. The string type says that any string can be used as a key, and number says that every stored value must be a number.
A dictionary is not automatically complete
A dictionary type describes the shape of possible entries. It does not mean that every possible key already exists.
const ages: { [person: string]: number } = {
ann: 30,
};
const age = ages["ben"];
console.log(age);At runtime, age is undefined because "ben" is absent. TypeScript compiler settings determine how strongly this possibility is represented in the type. Later, you will enable noUncheckedIndexedAccess so that indexed reads explicitly include undefined.
This distinction matters at boundaries such as parsed JSON, user input, and data loaded from a database. A key can be valid according to the dictionary rule and still be missing from a particular object.
The working model
Think of a typed dictionary as a relationship:
key: string -> value: numberThe relationship applies to every key accepted by the type. It is different from an object type that lists a finite set of named properties.
This model helps when choosing a type. Use a dictionary when the key set is open-ended or generated at runtime. Use named properties when the set is part of the data contract and should be checked explicitly.
Summary
Objects used as dictionaries store values under keys that are not known when the code is written. TypeScript can describe the key and value relationship with an index signature. Bracket notation supports dynamic access, but a valid key may still be absent. Safe dictionary code must account for missing values.
Exercise
What dictionary rule describes an object that accepts arbitrary usernames and stores a boolean for each username?
Show answer
It needs a string-keyed dictionary whose value type is boolean: { [username: string]: boolean }.