Index Signatures
Describe objects with dynamic keys you don't know ahead of time.
Syntax
interface Scores { [name: string]: number; }An index signature lets you type objects used as dictionaries, where the keys are not known in advance but all values share a type.
Reading it
{ [key: string]: number } means any string key maps to a number. It is ideal for lookup tables and counters.
Example
Loading editor…
Press Run to execute the code.
When to use it
- A translation dictionary maps arbitrary locale keys to string values, typed with an index signature.
- A cache object stores computed results by dynamic string keys without knowing them at design time.
- A score board maps player names (unknown at build time) to their numeric scores.
More examples
String index signature
Defines a string index signature so any string key can be added, but all values must be strings.
interface StringMap {
[key: string]: string;
}
const translations: StringMap = {
greeting: 'Hello',
farewell: 'Goodbye',
};
translations['thanks'] = 'Thank you'; // OK
translations['count'] = 42; // Error: Type 'number' is not assignable to type 'string'Numeric index signature
Uses a numeric index signature to model an array-like object where numeric keys map to string values.
interface NumberRecord {
[index: number]: string;
}
const items: NumberRecord = {};
items[0] = 'first';
items[1] = 'second';
console.log(items[0]);Mixed known and dynamic keys
Combines a required named property with an index signature, where the index value type must be a superset of the named property type.
interface Config {
name: string; // known property
[key: string]: string | number; // dynamic keys
}
const cfg: Config = {
name: 'app',
version: 2,
region: 'us-east-1',
};
Discussion