Codectionary / Developer documentation / TypeScript

Template-Pattern Index Signatures

An index signature can accept a pattern of string keys rather than every string.

What it is and why to use it

An index signature can accept a pattern of string keys rather than every string. A template pattern such as data-${string} constrains the prefix while allowing an open-ended suffix. This is useful for a configuration object with a documented family of custom fields.

Common mistakes and limitations

The pattern is a compile-time rule, not an HTML sanitiser or runtime key validator. A declared index signature does not mean a particular key is present. This feature is available from TypeScript 4.4.

Run this example

Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.

Terminal — compile and run

npx tsc example.ts --strict --target ES2022 --module commonjs
node example.js

Syntax

interface Options { [key: `data-${string}`]: string }

Examples

Template-Pattern Index Signatures

Standalone TypeScript 5.8+ example; expected output is explained below.

interface Options {
  title: string;
  [key: `data-${string}`]: string;
}
const options: Options = { title: "Guide", "data-topic": "CSS" };
console.log(options.title);
console.log(options["data-topic"] ?? "Missing");
  1. title is a separately declared required field.
  2. The data-topic key matches the index pattern and its value must be a string.
  3. The pattern does not generate any properties; it checks keys supplied by the program. This can make an extensible options API more precise than a broad string index signature.
  4. Expected output: Guide CSS

Best practices

  • The pattern is a compile-time rule, not an HTML sanitiser or runtime key validator. A declared index signature does not mean a particular key is present. This feature is available from TypeScript 4.4.
  • Keep external-input validation separate from compile-time type descriptions.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading