Combining Known and Dynamic Keys
Mix fixed properties with index signatures safely.
Fixed Plus Flexible
Often an object has a few guaranteed properties plus an open-ended set of extras. TypeScript lets you declare named properties and an index signature in the same type — with one important constraint.
A Known Key Alongside a Signature
Here length is always present, while any other string key maps to a number. The named property and the index signature coexist.
interface NumberMap {
length: number
[key: string]: number
}
const m: NumberMap = { length: 2, a: 1, b: 1 }
console.log(m.length, m.a)All lessons in this course
- Defining Index Signatures
- String vs Number Index Signatures
- Combining Known and Dynamic Keys
- Index Signatures vs Record