๐ŸŽ“ A1Learner
๐Ÿ”
0 of 42 lessons completed

TypeScript Index Signatures

An index signature types every key of a dictionary with one pattern. A value can hold any number of keys while each stored value keeps one type.

A dictionary built and read

The ScoreBoard type fixes no subject names in advance. Any string key is allowed, and every value must be a number.

interface ScoreBoard {
  [subject: string]: number;
}
const scores: ScoreBoard = { maths: 90, english: 84 };
scores.science = 77;
console.log(scores.maths);
console.log(scores.science);
console.log(scores.english);

A named member must fit the index type

The title member is a string, but the index type allows only numbers. The checker refuses the interface itself.

interface Scores {
  [subject: string]: number;
  title: string;
}

Number keys act as string keys

The same entry is read through a number key and through a string key. Both reads return the stored price.

interface PriceList {
  [item: string]: number;
}
const prices: PriceList = { 10: 250, 20: 400 };
console.log(prices[10]);
console.log(prices["10"]);
console.log(prices["20"]);

Example

interface WordCounts {
  [word: string]: number;
}
function countWords(words: string[]): WordCounts {
  const counts: WordCounts = {};
  for (const word of words) {
    counts[word] = (counts[word] ?? 0) + 1;
  }
  return counts;
}
const result = countWords(["pen", "book", "pen"]);
console.log(result.pen);
console.log(result.book);

Key points

  • An index signature is a pattern that types every key in an object at once.
  • Every named member of the type must fit the index type.
  • Number keys are string keys in disguise, because JavaScript converts them at runtime.
  • Record<string, number> is the alias spelling of the same dictionary idea.

In this example, the index signature lets countWords create keys as words appear, while every count stays a number.

Note

An index signature controls values by key pattern, not by a fixed list of names.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท TypeScript Playground

Exercise

Why does the checker refuse a string member inside a type whose index type is number?