Index signature

A description of objects with arbitrary keys and values of one type.

On this page

Example

#
TypeScript
interface Scores {
  [student: string]: number
}

const scores: Scores = { emma: 92, jack: 78 }
scores.mia = 85

const best = Object.entries(scores).sort(([, a], [, b]) => b - a)[0]
console.log(best)
Result
['emma', 92]

Definition and usage

#

The index signature [key: string]: number describes an object whose field names you don’t know ahead of time, but whose value type you do know. That’s what dictionaries look like: student scores, occurrence counters, translations.

The key can be of type string, number, or symbol. Fields declared alongside the signature must have a type compatible with it, because they’re also accessible through any key.

With the noUncheckedIndexedAccess option turned on, reading through an index signature returns type | undefined, which forces you to handle missing keys. For dictionaries with known keys, Record<K, V> is more convenient.

Syntax

#
Syntax
interface Dictionary {
  [key: string]: type
}

Good practices

#
  • When you know the list of keys, use Record<"html" | "css", number> instead of a general signature.
  • Turn on noUncheckedIndexedAccess, so the compiler reminds you about keys that might not exist.

Related entries

#

Spotted a mistake or missing an example? Write to us.