← 中文资源

简体中文版本

用 string & {} 保持联合类型开放

把 string 与空对象类型求交集:字面量自动补全保留,同时任意运行时字符串也能通过;裸联合在编译期就会拒绝未知字符串,两者不可兼得。

阅读英文原文

运行结果

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

theme=dark
theme=sepia
dark, sepia, light
true

实现说明

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