实现说明
用 string & {} 保持联合类型开放可以归结为函数 applyTheme。
常见问题
有第三方依赖吗?
没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 applyTheme。
主签名形如 function applyTheme(theme: Theme)
核心语句
return `theme=${theme}`;
代码示例
// string & {} keeps literal completions while still accepting any string
type Theme = 'light' | 'dark' | 'high-contrast' | (string & {});
function applyTheme(theme: Theme): string {
return `theme=${theme}`;
}
console.log(applyTheme('dark')); // literal: suggested and checked
console.log(applyTheme('sepia')); // arbitrary string: still accepted
// A plain union would reject unknown strings at compile time
type StrictTheme = 'light' | 'dark' | 'high-contrast';
// const s: StrictTheme = 'sepia'; // error TS2322: not assignable
const themes: Theme[] = ['dark', 'sepia', 'light'];
console.log(themes.join(', '));
console.log(applyTheme(themes[1] as StrictTheme) === 'theme=sepia');