runtime.boot

Full Stack Systems
Production Mindset

CodeWithMihir

Engineering thoughtful products from interface to infrastructure.

CodeWithMihir

TypeScript Tutorial

TypeScript Index Signatures Explained

Learn how index signatures work in TypeScript, including dynamic object keys, string indexes, number indexes, readonly indexes, and safer alternatives.

Welcome back! I am Mihir, and in this lesson we will learn index signatures in TypeScript.

Index signatures help you type objects when you know the value type but do not know all property names ahead of time.


The Problem

Imagine an object where keys are usernames and values are scores.

const scores = {
  mihir: 95,
  alex: 88,
};

You may not know every username in advance.

That is where an index signature helps.


Basic String Index Signature

type Scores = {
  [username: string]: number;
};

const scores: Scores = {
  mihir: 95,
  alex: 88,
};

This means:

  • keys are strings
  • values are numbers

Adding New Keys

scores.sara = 91;
scores["john"] = 84;

Both are valid because every string key must have a number value.

Invalid:

scores.mike = "high";

The value must be a number.


Index Signature with Known Properties

You can mix known properties with dynamic keys.

type ProductStock = {
  warehouse: string;
  [itemName: string]: string | number;
};

Why string | number?

Because warehouse is a string, and dynamic item quantities are numbers.

const stock: ProductStock = {
  warehouse: "Mumbai",
  keyboard: 10,
  mouse: 25,
};

All Properties Must Match the Index Type

This is invalid:

type BadStock = {
  warehouse: string;
  [itemName: string]: number;
};

warehouse is a string, but the index signature says every string key must have a number value.


Readonly Index Signature

Use readonly to prevent updates.

type ReadonlyScores = {
  readonly [username: string]: number;
};

const readonlyScores: ReadonlyScores = {
  mihir: 95,
};

Invalid:

readonlyScores.mihir = 100;

Number Index Signature

Arrays use number-like indexes, but you can also describe numeric keys.

type StringList = {
  [index: number]: string;
};

const names: StringList = {
  0: "Mihir",
  1: "Alex",
};

Each numeric index returns a string.


Prefer Specific Keys When Possible

If you know the exact keys, prefer a stricter type.

type Theme = {
  primary: string;
  secondary: string;
};

Use index signatures only when keys are genuinely dynamic.


Quick Recap

  • Index signatures type objects with dynamic keys.
  • String index signatures look like [key: string]: ValueType.
  • Every property must be compatible with the index signature.
  • Use readonly when dynamic values should not be changed.
  • Prefer exact object types when keys are known.

Next up, we enter narrowing with Type Narrowing →, one of the most important TypeScript skills.