← 中文资源

简体中文版本

模板字面量索引签名

模板字面量索引签名能约束整族动态键:CSS 变量必须带 -- 前缀,事件键只能取 on 加已知后缀,普通键名与拼错的键在编译期就被拒绝。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

驱动整个流程的是 for (const [name, value] of Object.entries(theme)) 这一个循环。

使用要点

  • 每一步打印都带着自己的标签:click on。

常见问题

它依赖第三方库吗?

没有引用任何第三方库,标准库就够了。

核心语句

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

代码示例

// 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');