TExcelTAD
Home › TypeScript › TS Index Signatures

TypeScript Index Signatures

Most object types list their properties by name: { title: string; year: number }. But sometimes you don't know the property names in advance — a dictionary of word counts, a cache keyed by ID, a map of HTTP headers. For those, TypeScript has index signatures: a way to say "any key of this type maps to a value of that type".

Syntax

An index signature uses square brackets with a parameter name (any name — key is conventional) and a key type:

ts · try it yourself
interface WordCounts {
  [word: string]: number;
}

const counts: WordCounts = {};
for (const w of "the cat saw the other cat".split(" ")) {
  counts[w] = (counts[w] ?? 0) + 1;
}

console.log(counts);
console.log(counts["cat"]);
{ the: 2, cat: 2, saw: 1, other: 1 }
2

The allowed key types are string, number, symbol, template literal patterns like `data-${string}`, and unions of these.

Values must match the signature

Every property — including explicitly named ones — must fit the index signature's value type:

ts · try it yourself
interface Prices {
  [item: string]: number;
  currency: string;
}

const p: Prices = { currency: "USD", apple: 1.2 };
console.log(p);
main.ts(3,3): error TS2411: Property 'currency' of type 'string' is not assignable to 'string' index type 'number'.
main.ts(6,7): error TS2322: Type '{ currency: string; apple: number; }' is not assignable to type 'Prices'.
  Property 'currency' is incompatible with index signature.
    Type 'string' is not assignable to type 'number'.

If you need mixed properties, widen the index signature ([item: string]: number | string) or move the dynamic part into its own property such as items: Record<string, number>. The second option is usually cleaner.

The Record shortcut

The utility type Record<K, V> produces the same thing and is often easier to read. With a union of literal keys, it also forces every key to be present:

Type Meaning
{ [key: string]: number } any string key → number
Record<string, number> the same thing
Record<"a" | "b", number> exactly the keys a and b
Partial<Record<"a" | "b", number>> a and/or b, both optional
ts · try it yourself
type Weekday = "mon" | "tue" | "wed";

const hours: Record<Weekday, number> = { mon: 8, tue: 7.5, wed: 6 };
const scores: Record<string, number> = { an: 9, binh: 7 };

let sum = 0;
for (const day of Object.keys(hours) as Weekday[]) {
  sum += hours[day];
}
console.log("total hours:", sum);
console.log(Object.entries(scores));
total hours: 21.5
[ [ 'an', 9 ], [ 'binh', 7 ] ]

The hidden undefined and noUncheckedIndexedAccess

With an index signature, TypeScript assumes every key exists. Reading a missing key gives undefined at runtime, but the type still says number — so this code compiles and then crashes:

ts · try it yourself
const stock: Record<string, number> = { apples: 5 };

const pears = stock["pears"];      // type: number (!)
try {
  console.log(pears.toFixed(1));
} catch (err) {
  console.log("Runtime error:", (err as Error).name);
}
Runtime error: TypeError

The compiler option noUncheckedIndexedAccess (not part of strict, but recommended for new projects) adds | undefined to every index-signature read, forcing you to check. Even without it, the safe habit is to handle the missing case yourself:

ts · try it yourself
const stock: Record<string, number> = { apples: 5 };

function available(item: string): string {
  const qty: number | undefined = stock[item];
  if (qty === undefined) return `${item}: not stocked`;
  return `${item}: ${qty.toFixed(1)}`;
}

console.log(available("apples"));
console.log(available("pears"));
apples: 5.0
pears: not stocked

Tip: If you need a real dynamic dictionary — with frequent additions and removals, or non-string keys — a Map<K, V> is often a better choice than a plain object. Its get method already returns V | undefined.

Template literal keys

Index signatures can restrict keys to a pattern. This is handy for objects that mix fixed properties with families of dynamic ones, such as data-* attributes:

ts · try it yourself
interface ElementAttrs {
  id: string;
  [attr: `data-${string}`]: string;
}

const attrs: ElementAttrs = {
  id: "card",
  "data-theme": "dark",
  "data-size": "lg",
};

for (const [k, v] of Object.entries(attrs)) {
  console.log(`${k}="${v}"`);
}
id="card"
data-theme="dark"
data-size="lg"

Here id doesn't have to match the pattern because it doesn't start with data-, while any key that does start with data- must have a string value.

Readonly index signatures

Prefix the signature with readonly to prevent writes through it — useful for lookup tables that should never be modified:

ts
const codes: { readonly [code: string]: string } = { VN: "Vietnam", JP: "Japan" };
codes.VN = "Viet Nam";   // error TS2542: Index signature in type ... only permits reading.

Test yourself

Which type describes an object with any string keys and boolean values?

  1. { string: boolean }
  2. { [key: string]: boolean }
  3. boolean[string]
  4. Map<boolean>

What does noUncheckedIndexedAccess change?

  1. It forbids index signatures
  2. Index reads get | undefined added to their type
  3. It makes all properties readonly
  4. It disables Record

What does Record<"x" | "y", number> require?

  1. Any keys
  2. At least one of x or y
  3. Both x and y with number values
  4. Keys that are numbers