TypeScriptInterfaces and classes
Index signature
A description of objects with arbitrary keys and values of one type.
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
#- Record<Keys, Type>Creates an object type with given keys, where every value has the same type.
- Object typesA description of an object’s shape: what fields it has and of what type.
- Mapped typesCreate a new object type by transforming every key of another type.
- keyofCreates a union of the key names of a given object type.
Spotted a mistake or missing an example? Write to us.