Defining Index Signatures
Describe objects whose keys are not known ahead of time.
Objects with Unknown Keys
Sometimes you do not know the property names in advance — a dictionary of scores, a cache, a lookup table. TypeScript's index signature lets you describe an object whose keys are arbitrary but whose values share one type.
Basic Index Signature Syntax
An index signature is written as { [key: string]: number }. It says: any string key maps to a number value. The name key is just a label — you can call it anything.
type Scores = { [name: string]: number }
const game: Scores = { alice: 10, bob: 7 }
console.log(game.alice) // 10All lessons in this course
- Defining Index Signatures
- String vs Number Index Signatures
- Combining Known and Dynamic Keys
- Index Signatures vs Record