Index signatures and records

Topic 3 of 4 in Modelling data7 min readIntermediateFree course

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.

Records and index signatures. Record<K, V> with known keys: type Drink = “tea” | “coffee”; const prices: Record<Drink, number> = { tea: 3.5, coffee: 4 } — both keys are required, and prices.tea is a number: an exact set of keys, where missing or extra keys are errors. An index signature allows any string key: type Stock = { [item: string]: number }; const stock: Stock = {}; stock[“pears”] = 8; const n = stock[“kiwi”] gives number | undefined: open-ended keys, where lookups may find nothing. That is with noUncheckedIndexedAccess on (recommended); without it TypeScript says number and trusts you. For a real dictionary that grows and shrinks at run time, a Map<string, number> is often better.

Index signatures

An index signature says “any key of this type maps to a value of that type”:

TypeScript
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:

TypeScript
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:

TypeScript
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:

TypeScript
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:

TypeScript
const price = stock["kiwi"];   // number  (without noUncheckedIndexedAccess)
price.toFixed(2);              // compiles… and crashes

With noUncheckedIndexedAccess (enabled in this course’s tsconfig), TypeScript adds undefined to every index-signature lookup:

TypeScript
const price = stock["kiwi"];   // number | undefined
price.toFixed(2);
// error TS18048: 'price' is possibly 'undefined'.

const safe = stock["kiwi"] ?? 0;   // number

Known 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[]:

TypeScript
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:

TypeScript
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:

TypeScript
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, noUncheckedIndexedAccess for honest lookups — and Map when the dictionary really is dynamic.

Exercise

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.

TypeScript
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 Map

Summary

  • 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; with string it’s an open dictionary.
  • Turn on noUncheckedIndexedAccess so dictionary lookups return V | undefined and must be checked.
  • Object.keys returns string[] and Object.entries returns [string, V][] — objects can have extra keys at run time.
  • Use a Map for dictionaries that grow and shrink, have non-string keys, or need a size.