Sub topic 9
Pattern index signatures with template literals
This chapter assumes you know basic TypeScript types, interfaces and type aliases, and JavaScript property access with dot and bracket notation. It also assumes you know union types and undefined. You should have seen a plain [key: string]: T index signature in earlier chapters.
Why a plain string signature is too broad
A string index signature accepts every string key. That is often too loose. Suppose an object holds HTML data attributes. Only keys that start with data- are meant to be dynamic, and the rest of the object should stay strictly typed.
With [key: string]: string, a typo such as "dat-id" type-checks, and so does any unrelated key. A pattern index signature narrows the dynamic part to keys that match a template literal type. The feature was added in TypeScript 4.4.
Declaring a pattern signature
The key type in the brackets is a template literal type instead of string:
interface DataAttributes {
[key: `data-${string}`]: string;
}
const attrs: DataAttributes = {
"data-id": "42",
"data-role": "admin",
};
attrs["data-theme"] = "dark";
console.log(attrs["data-id"]); // "42"
// attrs["id"] = "42";
// Error: Element implicitly has an 'any' type because expression of type '"id"'
// can't be used to index type 'DataAttributes'.
// attrs["data-count"] = 3;
// Error: Type 'number' is not assignable to type 'string'.The two errors come from different rules:
- A key that does not match the pattern is not covered by the signature, so TypeScript treats the property as missing.
- A key that matches the pattern must carry a value of the signature's value type.
What counts as a match
${string} stands for any string, including the empty string. A key matches when it has the literal parts in the right places.
| Key | Matches `` `data-${string}` `` | Reason |
|---|---|---|
| `"data-id"` | Yes | Starts with `data-`, then `id`. |
| `"data-"` | Yes | `${string}` can be empty. |
| `"data-a-b"` | Yes | `${string}` can contain hyphens. |
| `"Data-id"` | No | Matching is case-sensitive. |
| `"my-data-id"` | No | The prefix must be at the start. |
| `"data"` | No | The hyphen is missing. |
You can place the pattern anywhere in the template: prefix, suffix, or both.
interface Ids {
[key: `${string}Id`]: number;
}
interface Slots {
[key: `slot-${number}`]: string;
}
const ids: Ids = { userId: 1, orderId: 2 };
const slots: Slots = { "slot-1": "header", "slot-2": "footer" };
console.log(ids.userId, slots["slot-1"]);${number} accepts any string that TypeScript considers a numeric literal, such as "1", "2.5" or "-3". It rejects "slot-a". It is a type-level check only. At runtime the object is an ordinary JavaScript object, and nothing validates keys.
Unions of patterns
An index signature can use a union of patterns. This is allowed as long as each member is an infinite-domain type such as string, number, symbol or a template pattern.
interface Handlers {
[key: `on${string}` | `before${string}`]: () => void;
}
const handlers: Handlers = {
onClick: () => console.log("clicked"),
beforeSave: () => console.log("saving"),
};
handlers.onClick();Every key that matches either pattern gets the same value type. If you need different value types per pattern, declare several signatures, as covered below.
Mixing patterns with known properties
A pattern signature only constrains the keys that match it. A known property whose name does not match is unaffected and can have any type:
interface Widget {
id: string;
visible: boolean;
[key: `data-${string}`]: string;
}
const widget: Widget = {
id: "w1",
visible: true,
"data-size": "large",
};
console.log(widget.visible, widget["data-size"]);Compare this with a full [key: string]: string signature. There, visible: boolean would be an error, because every known property must be assignable to the index type. With a pattern signature, the check applies only to known properties whose names match the pattern:
// interface Broken {
// [key: `data-${string}`]: string;
// "data-count": number;
// // Error: Property 'data-count' of type 'number' is not assignable to
// // 'data-${string}' index type 'string'.
// }This is the main reason to prefer a pattern over a wide string signature: it removes the need to widen the value type to string | number | boolean just to fit the known properties.
Several signatures on one type
A type can have a string signature and one or more pattern signatures. The rule is that the value type of each narrower signature must be assignable to the value type of the broader one.
interface Mixed {
[key: string]: string | number;
[key: `data-${string}`]: string;
[key: `count-${string}`]: number;
}
const mixed: Mixed = {
title: "Report",
"data-id": "7",
"count-rows": 12,
};
const a = mixed["data-id"]; // string
const b = mixed["count-rows"]; // number
const c = mixed["title"]; // string | number
console.log(a, b, c);TypeScript picks the signatures whose key type matches the key you use. A literal key that matches a pattern gets the pattern's value type. Any other key falls back to the string signature.
Dynamic keys: narrowing a `string`
The pattern only helps when TypeScript can see that the key matches. A plain string variable does not match:
interface DataAttributes {
[key: `data-${string}`]: string;
}
function isDataKey(key: string): key is `data-${string}` {
return key.startsWith("data-");
}
function lookup(el: DataAttributes, key: string): string | undefined {
// return el[key]; // Error: 'string' can't be used to index type 'DataAttributes'.
return isDataKey(key) ? el[key] : undefined;
}
function readData(el: DataAttributes, name: string): string | undefined {
const key = `data-${name}` as const; // type: `data-${string}`
return el[key];
}
const el: DataAttributes = { "data-id": "42" };
console.log(lookup(el, "data-id")); // "42"
console.log(lookup(el, "id")); // undefined
console.log(readData(el, "id")); // "42"There are two ways to get a key of the right type:
- A user-defined type guard such as
isDataKeychecks the key at runtime and narrows it. as conston a template expression makes TypeScript give it the type `data-${string}instead of widening it tostring`. This is correct here because the prefix is guaranteed by construction.
Avoid asserting key as data-${string}`` on an unchecked string. That silences the compiler without verifying anything.
Missing keys and `noUncheckedIndexedAccess`
A pattern signature says that every matching key has a value, but a given object may not have it. Reading el["data-missing"] gives string and returns undefined at runtime. As with other index signatures, noUncheckedIndexedAccess closes this gap:
// tsconfig.json: { "compilerOptions": { "noUncheckedIndexedAccess": true } }
interface DataAttributes {
[key: `data-${string}`]: string;
}
const el: DataAttributes = { "data-id": "42" };
const value = el["data-id"]; // string | undefined
if (value !== undefined) {
console.log(value.toUpperCase());
}With the flag on, reads through the signature produce string | undefined. Known properties declared next to the signature, like id: string on Widget, keep their declared types.
Existence checks and the prototype
The existence checks from earlier chapters apply here unchanged. Use Object.hasOwn(el, key) for own keys. The in operator also finds inherited keys. Those inherited names (toString, constructor) rarely match a pattern such as data-${string}, so a prefix pattern gives you a small safety margin. It does not protect a signature like ` ${string}Id , which "valueOf" does not match but "constructorId"` would.
Readonly and other key types
The modifiers you already know work the same way. readonly blocks writes through matching keys:
interface FrozenData {
readonly [key: `data-${string}`]: string;
}
const frozen: FrozenData = { "data-id": "1" };
console.log(frozen["data-id"]);
// frozen["data-id"] = "2"; // Error: Index signature in type 'FrozenData' only permits reading.Symbols can also be pattern-like keys: [key: symbol]: T is valid. Template patterns apply only to string keys.
Pattern signatures versus mapped types
A mapped type over a template pattern produces an equivalent type:
type DataAttributesMapped = { [K in `data-${string}`]: string };
const m: DataAttributesMapped = { "data-id": "42" };
console.log(m["data-id"]);Use the mapped form when it derives from another type, for example { [K in data-${Names}]: string } with a finite union Names. In that case the result has exactly those keys and is not a pattern at all. Use the interface form when you want to add known properties or readonly members, or to extend the type.
When a pattern signature is the wrong tool
- The set of keys is known and finite. Use
Record<"a" | "b", T>or a plain interface. A pattern signature would accept keys you never meant to allow. - Keys are not strings, or you add and remove entries often. Use
Map, as discussed in a later chapter. - Each key needs a different value type. Several pattern signatures work if the patterns are distinct. If they overlap, an access matches more than one signature, and the value type is the intersection of the matching value types. Prefer non-overlapping patterns.
Common errors
- Indexing with a plain
stringvariable and getting "can't be used to index type". Narrow with a type guard or build the key withas const. - Putting a known property such as
"data-count": numberin the same type as adata-${string}signature of a different value type. - Forgetting that
${string}can be empty, so"data-"is a valid key. - Expecting
${number}to reject strings like"1e3". It accepts them. - Assuming the pattern is checked at runtime.
Exercise
Define an interface Theme with a required name: string property and a pattern index signature so that any key starting with --color- maps to a string. Then write a function getColor(theme: Theme, key: string): string | undefined that returns the value only for keys that match the pattern. Why does name not conflict with the signature?
Show answer
interface Theme { name: string; [key: --color-${string}]: string; }
function isColorKey(key: string): key is --color-${string} { return key.startsWith("--color-"); }
function getColor(theme: Theme, key: string): string | undefined { return isColorKey(key) ? theme[key] : undefined; }
The property name does not start with --color-, so the pattern signature does not apply to it. Only known properties whose names match the pattern must be assignable to the signature's value type, so name can be any type.
Exercise
Given interface Counts { [key: string]: string | number; [key: count-${string}]: number; }, what are the types of c["count-a"] and c["label"] for a value c: Counts? Is it valid to change the second signature's value type to boolean?
Show answer
c["count-a"] is number because the key matches the pattern. c["label"] is string | number because it falls back to the string signature. Changing the pattern's value type to boolean is an error, because the narrower signature's value type must be assignable to the string signature's value type (string | number), and boolean is not.