← 中文资源

简体中文版本

const 类型参数保留字面量键

const 类型参数阻止推断拓宽字面量:config.mode 保持 "strict" 而不是 string,键名联合也一并保留,配置字面量在编译期即可约束。

阅读英文原文

运行结果

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

mode: strict
config[port]: 8080

实现说明

顶层就这几处状态:config。

使用要点

  • 每一步打印都带着自己的标签:mode:、config[。

常见问题

有语言之外需要解析的导入吗?

没有。每个导入都解析到语言自带的模块。 状态都挂在模块顶层:config。

核心语句

type KnownKeys = keyof typeof config;

代码示例

// 普通推断会把属性拓宽成 string;const 类型参数保留字面量
function defineConfig<const T extends Record<string, string | number>>(config: T): T {
  return config;
}

const config = defineConfig({
  host: 'localhost',
  port: 8080,
  mode: 'strict',
});

// config.mode 的类型是字面量 'strict',而不是 string
type Mode = typeof config.mode;
const mode: Mode = 'strict';
console.log('mode:', mode);

// 键名联合同样来自推断
type KnownKeys = keyof typeof config;
const key: KnownKeys = 'port';
console.log('config[' + key + ']:', config[key]);