实现说明
驱动整个流程的是 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');