Advertisement
Advanced TypeScript, Index Signatures & Record Types

How do you constrain an index signature's key type to only specific string patterns using template literal types?

Short answer

Combine a mapped type (since plain index signatures only support generic string/number/symbol, not literal patterns) with a template literal type as the key pattern, letting you type objects whose keys must follow a specific naming convention, like a CSS-variable-style prefix.

Save TypeScript mock interview
Advertisement
AModel answer
Combine a mapped type (since plain index signatures only support generic string/number/symbol, not literal patterns) with a template literal type as the key pattern, letting you type objects whose keys must follow a specific naming convention, like a CSS-variable-style prefix.
type CssVariables = {
  [K in `--${string}`]: string
};
const styles: CssVariables = {
  '--primary-color': '#3366ff',
  '--font-size': '16px'
  // 'color': 'red' // Error: doesn't match the '--${string}' pattern
};
Real-world example
Typing a CSS custom-properties object where every key must start with '--', catching typos in variable naming.
Likely follow-ups
  • How does this differ in capability from a plain `[key: string]: string` index signature?
Related topics