← 中文资源

简体中文版本

const 保留字面量而 let 扩宽

const 声明保留字面量类型,let 会扩宽成 string:把值传给联合类型参数会被拒,写上注解或在属性上用联合与 as const 才能拦住这次扩宽。

阅读英文原文

运行结果

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

opened in readonly mode
edit
published
light
eu pro

实现说明

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