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.
Code
// 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-buttonFollowing 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.