Sub topic 9
Pattern Index Signatures with Template Literals
This chapter assumes you know basic TypeScript interfaces, type aliases, union types, and JavaScript property access with dot and bracket notation. It also assumes you understand that a type such as string | undefined means a value can be a string or can be missing.
A template literal pattern index signature types only properties whose names match a string pattern. It is useful when an object has dynamic keys, but those keys must follow a naming rule.
The problem with an unrestricted index signature
A normal string index signature accepts every string key:
interface Metadata {
[key: string]: string;
}This type allows keys such as "data-id", "data-role", and "anything-at-all". Sometimes that is too broad. For example, an HTML-like options object might allow custom data-* attributes but reject unrelated keys.
A template literal pattern narrows the accepted keys:
interface DataAttributes {
[key: `data-${string}`]: string;
}
const attrs: DataAttributes = {
"data-id": "42",
"data-role": "admin",
};
// const invalid: DataAttributes = {
// role: "admin",
// };
// Error: 'role' does not match the pattern `data-${string}`.The ${string} part means any string after the required data- prefix. The pattern does not enumerate the possible names. It describes a whole family of names.
Mixing known properties with patterned properties
A pattern index signature applies only to matching property names. Known properties outside the pattern can have different types:
interface ElementOptions {
id: string;
disabled: boolean;
[key: `data-${string}`]: string;
}
const options: ElementOptions = {
id: "card-1",
disabled: false,
"data-role": "admin",
"data-owner": "ann",
};Here, id must be a string, disabled must be a boolean, and every property beginning with data- must be a string. Unlike a [key: string] signature, the pattern does not force id and disabled to be strings.
This makes patterns useful for configuration objects with a fixed core and a controlled extension area.
Patterns can express several naming rules
A pattern can include more than a fixed prefix:
interface EnvironmentVariables {
[key: `APP_${Uppercase<string>}`]: string;
}
const environment: EnvironmentVariables = {
APP_PORT: "3000",
APP_MODE: "production",
};
// const bad: EnvironmentVariables = {
// app_port: "3000",
// };
// Error: the key does not match the uppercase pattern.In practice, simple patterns such as ` data-${string} and aria-${string} ` are easier to read. You can also combine patterns with known properties:
interface AccessibleProps {
role: string;
[key: `aria-${string}`]: string;
}The compiler checks these patterns when it checks object literals, assignments, and property declarations. The pattern does not validate strings received from a user or a file at runtime.
Common errors and safe design
The value type still applies to every matching key:
interface Counts {
[key: `count-${string}`]: number;
}
const counts: Counts = {
"count-open": 3,
"count-closed": 1,
};
// counts["count-total"] = "4";
// Error: Type 'string' is not assignable to type 'number'.Use readonly when callers may read the attributes but must not change them:
interface ReadonlyDataAttributes {
readonly [key: `data-${string}`]: string;
}
const data: ReadonlyDataAttributes = {
"data-id": "42",
};
// data["data-id"] = "43";
// Error: the index signature only permits reading.A pattern signature does not prove that a key exists. With noUncheckedIndexedAccess enabled, a lookup is possibly undefined:
interface DataAttributes {
[key: `data-${string}`]: string;
}
const attrs: DataAttributes = { "data-id": "42" };
const key = "data-label" as `data-${string}`;
const value = attrs[key]; // string | undefined
if (value !== undefined) {
console.log(value.toUpperCase());
}Choosing a related type
Use a pattern index signature when the set of keys is open-ended but follows a naming rule. Use Record when the keys are already represented by a finite union or when you want a general dictionary.
| Type | Best use | Column |
|---|---|---|
| Pattern index signature | Arbitrary keys matching a template such as `data-${string}` | |
| `Record<"low" \ | "high", number>` | A fixed, known set of keys |
| Mapped type | Transforming or making a known key union optional or readonly |
A mapped type can also describe a finite collection of patterned names only when you first create a finite union. A pattern such as ` data-${string} ` remains open-ended, so it is not an enumeration of every possible key.
Exercise
In the ElementOptions interface, why can disabled be a boolean even though the interface has an index signature?
Show answer
The index signature only applies to keys matching data-${string}. disabled does not match that pattern, so its declared boolean type is checked separately.