TypeScript theorytheory 0/50 · 0%
Types · medium

34. Index signatures

Typing objects with dynamic, unknown-in-advance keys.

An index signature describes the type of values for keys that aren't known ahead of time, useful for dictionaries keyed by dynamic strings such as addresses or symbols.

ts
interface Balances {
  [address: string]: number;
}

const balances: Balances = {};
balances["0xabc"] = 100;
balances["0xdef"] = 50;

interface MixedRecord {
  owner: string;          // known key
  [key: string]: string;  // all other keys must also be string
}

Every declared, specific property must be compatible with the index signature's value type — that's why in `MixedRecord`, `owner` had to be typed `string` too, matching `[key: string]: string`. With `noUncheckedIndexedAccess` enabled, indexed lookups return `T | undefined` instead of `T`, correctly reflecting that the key might not exist.

Check your understanding

  1. 1. What does `[address: string]: number` in an interface declare?

  2. 2. If an interface has `[key: string]: string`, what must every explicitly named string property be?

  3. 3. What does `noUncheckedIndexedAccess` change about indexed lookups?