TypeScript Index Signature Dynamic Signature Property with version 4.4<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

TypeScript Index Signature Dynamic Signature Property with version 4.4

Posted on: January 14, 2022

JavaScript as a way to key-value in a dictionary/map way that is very flexible. It works by using a string for the name of the property, and then you can assign a value. TypeScript is providing type association to the value, but before 4.4 you could not.

We can summarize what was possible before TypeScript version 4.4 with index signature with the following example:

1interface KeyValue {
2 [k: string]: string; // Very wide
3}

As it appears, you can specify the key to be a string or a number but not specific other names. Concerning the value, it could be anything. You could still write a specific key by directly writing the name. In the following example, we accept any number or "test".

1interface KeyValue {
2 [k: number]: string; // Allows any key as a number
3 ["test"]: string; // Allows the key "test"
4}
5const kv1: KeyValue = {
6 1: "good",
7 "test": "sure"
8};

What is new with TypeScript version 4.4 is defining a pattern instead of being widely open to accept any string or specify the exact string. A use case is with HTML where there is a known set of attribute but also the standard allows anything with a prefix of data-.

1interface HtmlAttributes {
2 color?: string;
3 left?: number;
4 top?: number;
5}
6
7interface DivHtmlAttributes extends HtmlAttributes {
8 [other: `data-${string}`]: unknown;
9}
10
11let myDiv: DivHtmlAttributes = {
12 color: "red",
13 "data-blah": true
14};

The syntax might not be something that you are naturally using to define a type. It relies on the backticks with the string you desire to be required and between ${} the dynamic portion type; in that case, it is a string.