实现说明
const 保留字面量而 let 扩宽的核心是函数 openIn。
常见问题
有语言之外需要解析的导入吗?
没有。每个导入都解析到语言自带的模块。 文件在加载时定义 openIn。
主签名形如 function openIn(mode: Mode)
核心语句
const frozen = { region: 'eu', tier: 'pro' } as const;
return `opened in ${mode} mode`;
代码示例
type Mode = 'readonly' | 'edit';
function openIn(mode: Mode): string {
return `opened in ${mode} mode`;
}
// const preserves the literal type: mode is 'readonly', not string
const mode = 'readonly';
console.log(openIn(mode));
// let widens the literal to string, so it no longer fits Mode
let label = 'edit';
console.log(label);
// openIn(label); // string is not assignable to 'readonly' | 'edit'
// Annotating the declaration stops the widening at the source
let state: 'draft' | 'published' = 'draft';
state = 'published';
console.log(state);
// Object properties widen too; an explicit union type keeps them usable
const flags = { theme: 'dark' as 'dark' | 'light' };
flags.theme = 'light';
console.log(flags.theme);
// as const freezes every property at its literal instead
const frozen = { region: 'eu', tier: 'pro' } as const;
type Region = (typeof frozen)['region']; // 'eu'
type _Region = Region;
console.log(frozen.region, frozen.tier);