Template Literal Index Signatures

Template literal index signatures type whole families of dynamic keys — CSS vars must carry the -- prefix and event keys only known on-suffixes.

TypescriptConfig Management

Code

typescriptsnippet
21 lines
// Template literal index signatures type whole families of dynamic keys
type CssVars = Record<`--${string}`, string>;

const theme: CssVars = {
  '--accent': '#4c8dff',
  '--surface': '#101418',
};
// theme.accent = 'red'; // TS2339: 'accent' does not exist on CssVars

for (const [name, value] of Object.entries(theme)) {
  console.log(`${name}: ${value}`);
}

// Unions inside the template restrict the key set further
type Handler = (target: string) => void;
const handlers: Record<`on${'Click' | 'Hover'}`, Handler> = {
  onClick: (target) => console.log('click on', target),
  onHover: (target) => console.log('hover on', target),
};

handlers.onClick('save-button');

Output

Captured from a sandboxed run of this snippet in the build pipeline.

--accent: #4c8dff
--surface: #101418
click on save-button

Following the data

Repetition is confined to for (const [name, value] of Object.entries(theme)) — the rest of the file is straight-line.

Points of care

  • Imports, where present, target standard-library modules only.

Using it

The demo output is labeled (click on, hover on); each label names the call that printed it.

Key statements

type Handler = (target: string) => void;

Interactive Tools for This Topic

FAQ

Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it.