Index signatures and records
Overview
Objects in JavaScript play two roles. Sometimes they’re records with known properties ({ name, email }). Sometimes they’re dictionaries: a lookup table from keys to values, where the keys come from data — word counts, prices by product code, settings by name. This lesson covers typing the dictionary kind.
Index signatures
An index signature says “any key of this type maps to a value of that type”:
type Stock = {
[item: string]: number;
};
const stock: Stock = {};
stock["pears"] = 8;
stock.apples = 12; // dot syntax works too
stock.kiwi = "none";
// error TS2322: Type 'string' is not assignable to type 'number'.The name in brackets (item) is only documentation. Keys can be string, number, symbol or template-literal patterns like [key: `data-${string}`]: string.
You can mix an index signature with known properties, as long as the known ones fit the signature:
type Headers = {
"content-type": string; // must be present
[name: string]: string; // any other header
};Record
The built-in Record<K, V> type is a shorter way to write the same thing:
type Stock = Record<string, number>; // same as { [key: string]: number }Its real power shows when K is a union of literals. Then the object must have exactly those keys:
type Day = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";
const hours: Record<Day, string | null> = {
mon: "9-17", tue: "9-17", wed: "9-17", thu: "9-20", fri: "9-17", sat: "10-14",
};
// error TS2741: Property 'sun' is missing in type '{ … }' but required in type 'Record<Day, string | null>'.Add a value to the Day union, and every Record<Day, …> in the codebase reports the missing key — a cousin of exhaustiveness checking.
Safe lookups
Looking up a key that isn’t there returns undefined at run time. Plain strict mode doesn’t model that for index signatures:
const price = stock["kiwi"]; // number (without noUncheckedIndexedAccess)
price.toFixed(2); // compiles… and crashesWith noUncheckedIndexedAccess (enabled in this course’s tsconfig), TypeScript adds undefined to every index-signature lookup:
const price = stock["kiwi"]; // number | undefined
price.toFixed(2);
// error TS18048: 'price' is possibly 'undefined'.
const safe = stock["kiwi"] ?? 0; // numberKnown keys from a Record<Day, …> are not affected — hours.mon is still string | null, because the type guarantees the key exists.
Object.keys and Object.entries
You might expect Object.keys(hours) to return Day[]. It returns string[]:
for (const key of Object.keys(hours)) {
hours[key];
// error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Record<Day, string | null>'.
}That’s deliberate. Because types are structural, an object with extra properties can be passed where a Record<Day, …> is expected, so at run time Object.keys might return keys outside Day. Options:
- Loop over a list of keys you control:
const DAYS = ["mon", …] as const; for (const day of DAYS) hours[day]. - Use
Object.entries(obj), which gives[string, V][]— the values are typed even if the keys are plain strings. - If you’re sure the object has no extra keys, cast deliberately:
Object.keys(hours) as Day[].
Map: the purpose-built dictionary
For dictionaries that change at run time, JavaScript’s Map is often the better tool, and it’s fully typed:
const counts = new Map<string, number>();
counts.set("tea", 3);
counts.get("tea"); // number | undefined — always, no option needed
counts.has("tea"); // true
counts.delete("tea");
counts.size; // 0
for (const [key, value] of counts) { … }| Use a plain object / Record when… | Use a Map when… |
|---|---|
| the keys are a fixed, known set | keys are added and removed at run time |
| you serialise to JSON directly | keys aren’t strings (objects, numbers as numbers) |
| you want the excess-property and missing-key checks | you need size or insertion-ordered iteration |
| it’s configuration or a lookup table | it’s a cache, counter or registry |
Map also avoids the oddities of objects as dictionaries, such as inherited keys like "constructor" and "__proto__".
Record<string, unknown> for “some object”
When a function accepts any plain object whose contents you’ll inspect, Record<string, unknown> is the safe type:
function logFields(obj: Record<string, unknown>) {
for (const [key, value] of Object.entries(obj)) {
console.log(key, typeof value);
}
}Remember:
Record<Union, V>for fixed key sets,Record<string, V>or an index signature for open ones,noUncheckedIndexedAccessfor honest lookups — andMapwhen the dictionary really is dynamic.
Word counts and opening hours
(1) Write countWords(text: string): Record<string, number> that counts each lower-cased word (strip . and ,). Print the count for "the" and the most common word, handling the possibly-missing lookup without !. (2) Define type Day = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun" and const hours: Record<Day, string | null> (null = closed) — TypeScript must force you to list all seven days. Write openDays(h: Record<Day, string | null>): Day[]. (3) Re-do the word count with a Map<string, number> and print the size of the map.
const text = "The cat sat on the mat. The dog sat, too.";
// 1. countWords with a Record
// 2. Opening hours
// 3. The same with a Mapconst text = "The cat sat on the mat. The dog sat, too.";
// 1. countWords with a Record
function countWords(text: string): Record<string, number> {
const counts: Record<string, number> = {};
for (const word of text.toLowerCase().replace(/[.,]/g, "").split(/\s+/)) {
if (word === "") continue;
counts[word] = (counts[word] ?? 0) + 1; // counts[word]: number | undefined
}
return counts;
}
const counts = countWords(text);
console.log("the:", counts["the"] ?? 0); // the: 3
let best = "";
let bestCount = 0;
for (const [word, count] of Object.entries(counts)) {
if (count > bestCount) {
best = word;
bestCount = count;
}
}
console.log("most common:", best, bestCount); // most common: the 3
// 2. Opening hours
type Day = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";
const hours: Record<Day, string | null> = {
mon: "9-17", tue: "9-17", wed: "9-17", thu: "9-20", fri: "9-17", sat: "10-14", sun: null,
};
function openDays(h: Record<Day, string | null>): Day[] {
const days: Day[] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
return days.filter((day) => h[day] !== null);
}
console.log(openDays(hours).join(" ")); // mon tue wed thu fri sat
// 3. The same with a Map
const map = new Map<string, number>();
for (const word of text.toLowerCase().replace(/[.,]/g, "").split(/\s+/)) {
if (word) map.set(word, (map.get(word) ?? 0) + 1);
}
console.log("unique words:", map.size, "| cat:", map.get("cat")); // unique words: 7 | cat: 1Summary
- An index signature
{ [key: string]: number }types an object with any number of keys of one value type. Record<K, V>is shorthand: with a literal union for K it requires exactly those keys; withstringit’s an open dictionary.- Turn on
noUncheckedIndexedAccessso dictionary lookups returnV | undefinedand must be checked. Object.keysreturnsstring[]andObject.entriesreturns[string, V][]— objects can have extra keys at run time.- Use a
Mapfor dictionaries that grow and shrink, have non-string keys, or need a size.