实现说明
顶层就这几处状态: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]);