Sub topic 1
Objects used as dictionaries
Many JavaScript programs use a plain object as a lookup table. The keys are strings chosen at runtime, such as words in a document, user IDs from a database, or header names from an HTTP request. TypeScript normally types objects by their known property names, so these lookup tables need a different kind of type. This chapter explains what a dictionary object is, why TypeScript's usual object types reject it, and which problems the rest of the tutorial solves.
Prerequisites
This chapter assumes you already know:
- Basic TypeScript types, interfaces, and type aliases.
- JavaScript objects and property access with dot notation (
obj.name) and bracket notation (obj["name"]). - Union types and the
undefinedtype.
The examples assume strict mode is on in your tsconfig.json, which includes noImplicitAny. Most projects start from a template that sets it.
What a dictionary object is
An object can serve two different roles in JavaScript.
In the first role it is a record. A record has a fixed, known set of property names, each with its own meaning and often its own type:
const user = { id: 7, name: "Ada", active: true };You wrote the keys id, name, and active in the source code. TypeScript infers the type { id: number; name: string; active: boolean }, and it can check every access against that list.
In the second role it is a dictionary. A dictionary maps arbitrary keys to values of one kind. The keys come from data, and nobody lists them in the source:
const wordCounts = { the: 3, cat: 1, sat: 1 };The values here are all numbers and the keys are words, but the next document will have different words. Adding a key is a normal operation for a dictionary and a mistake for a record.
| Row | Record | Dictionary |
|---|---|---|
| Keys | Fixed, written in the source | Arbitrary, known only at runtime |
| Values | Often different types per key | One type (or one union) for all keys |
| Adding a key | Usually a bug | Normal operation |
| Typical examples | A user, a config section, an API response | Word counts, items by ID, headers by name |
The distinction is about how you use the object. It is not a feature of JavaScript. The same object literal can play either role, and TypeScript only needs to know which one you intend.
Why TypeScript rejects dictionary access
TypeScript infers a record type from an object literal, so it knows exactly which keys exist. When you index that object with a plain string, it cannot prove the key is one of them:
const stock = { apples: 5, pears: 2 };
function countOf(name: string): number {
return stock[name];
// Error: Element implicitly has an 'any' type because expression of type
// 'string' can't be used to index type '{ apples: number; pears: number; }'.
}The check is reasonable. If name is "bananas", the lookup returns undefined at runtime, and the declared return type number would be wrong. TypeScript refuses to guess.
Adding a new key fails for a related reason:
const stock = { apples: 5, pears: 2 };
// stock.bananas = 3;
// Error: Property 'bananas' does not exist on type '{ apples: number; pears: number; }'.The inferred type lists two properties, and the assignment tries to add a third. Both errors have the same cause. The type says "these keys and no others", but a dictionary means "any key of this kind".
You could silence the errors with as any or a type assertion. That turns off checking exactly where bugs occur, so it is not a fix. The proper fix is to describe the dictionary shape in the type.
The shape of the fix
TypeScript lets you declare "any string key maps to a number" with an index signature. The following example previews the syntax. The next chapter covers it in full.
const stock: { [name: string]: number } = { apples: 5, pears: 2 };
function countOf(name: string): number {
return stock[name];
}
stock["bananas"] = 3;
console.log(countOf("bananas")); // 3The part [name: string]: number reads as "for any key of type string, the value has type number". The name name inside the brackets is only a label for readability. It has no effect on the type. Now both the lookup and the assignment compile, and a wrong value type is still caught:
const stock: { [name: string]: number } = {};
// stock["kiwis"] = "many";
// Error: Type 'string' is not assignable to type 'number'.The dictionary can have any keys, but every value must be a number.
A dictionary in practice: counting words
A word counter shows the pattern in a realistic setting. It builds the dictionary from data, so the keys cannot be known in advance:
function countWords(text: string): { [word: string]: number } {
const counts: { [word: string]: number } = {};
for (const word of text.split(" ")) {
counts[word] = (counts[word] ?? 0) + 1;
}
return counts;
}
console.log(countWords("the cat saw the dog"));
// { the: 2, cat: 1, saw: 1, dog: 1 }The loop reads counts[word] before the key necessarily exists. That read is the main risk of dictionaries, and this chapter sets up two of the problems that later chapters solve.
Two risks that dictionary types do not remove
An index signature makes the compiler accept arbitrary keys, but it does not prove those keys are present or safe to read.
Missing keys look like present ones
With the type { [word: string]: number }, TypeScript says that counts["zebra"] has type number. If "zebra" was never added, the real value is undefined:
const counts: { [word: string]: number } = { cat: 1 };
const zebra = counts["zebra"]; // typed as number
console.log(zebra); // undefined at runtime
// console.log(zebra.toFixed(2)); // compiles, but throws a TypeError at runtimeThe type and the runtime value disagree, and the compiler cannot see the problem. The chapter on noUncheckedIndexedAccess shows how to make TypeScript report number | undefined instead, which forces you to handle the missing case.
Plain objects have inherited keys
A new object created with {} is not empty. It inherits properties from Object.prototype, such as constructor and toString. Reading one of those names from your dictionary returns something you never stored:
const counts: { [word: string]: number } = {};
for (const word of ["the", "constructor", "the"]) {
counts[word] = (counts[word] ?? 0) + 1;
}
console.log(counts["the"]); // 2
console.log(typeof counts["constructor"]); // "string"For the word "constructor", the expression counts[word] finds the inherited Object function, not undefined. The ?? 0 fallback is skipped because the value exists, and adding 1 to a function produces a string. TypeScript reports no error, because it believes every value is a number. The program then holds corrupted data.
A related quirk applies to the key "__proto__". Assigning to it on a plain object changes the object's prototype instead of creating an entry, so the entry never appears in the dictionary.
How the pieces fit together
The decision starts with one question: do you know the key names when you write the code? The answer selects the tool, and the later chapters fill in each branch.
The three dictionary options differ in how they handle missing keys, inherited keys, and key patterns. Later chapters compare them in detail. The last chapter turns the comparison into decision criteria.
What the rest of the tutorial covers
The remaining chapters follow the problems raised above.
- The syntax of an index signature.
- Which key types are allowed.
- How known properties can coexist with an index signature.
- How to handle missing keys.
- How to check that a key exists, and why inherited keys complicate that.
- How to build objects with no prototype.
- Readonly dictionaries and template literal pattern keys.
Recordand mapped types.- When a
Mapis the better tool. - How to choose among all of these.
Common mistakes at this stage
- Using
as anyto silence the indexing error. The error is correct, because the type does not describe a dictionary. Describe the dictionary instead. - Treating an object literal as a dictionary because it has many keys. An object with a large, fixed key set can still be a record. What matters is whether the keys are known when you write the code.
- Assuming a typed lookup always returns a value. The declared type describes what a stored value looks like. It says nothing about whether a given key was stored.
- Starting a dictionary from
{}with user-supplied keys. Inherited names likeconstructorcan produce wrong results without any compile error.
Exercises
Exercise
A function price(item: string) reads catalog[item], where catalog is declared as const catalog = { tea: 3, coffee: 4 };. TypeScript reports an error under noImplicitAny. Why does it fail, and what in the type of catalog must change?
Show answer
The inferred type is { tea: number; coffee: number }, which lists exactly two keys. A plain string might be any other key, so TypeScript cannot prove the access is valid. The type must describe a dictionary, for example { [item: string]: number }, which says any string key maps to a number.
Exercise
Given const counts: { [word: string]: number } = {};, the code counts["constructor"] = (counts["constructor"] ?? 0) + 1; compiles. Why does it produce a wrong value at runtime, and why does TypeScript not warn about it?
Show answer
A plain object inherits constructor from Object.prototype, so counts["constructor"] is the Object function, not undefined. The ?? 0 fallback is skipped, and adding 1 to a function yields a string. TypeScript does not warn because the index signature declares every value as a number, and the compiler does not model inherited properties.
Exercise
For each object, say whether it is a record or a dictionary: (a) HTTP response headers keyed by header name, (b) a { width: number; height: number } size, (c) a map from product ID to price loaded from a database.
Show answer
(a) Dictionary, because header names are only known at runtime. (b) Record, because the two keys are fixed and written in the source. (c) Dictionary, because the product IDs come from data.