TypeScript_as const 的使用
as const的作用是:
把「可变的、宽泛的值」锁死成「最精确、不可变的字面量类型」
在没有as const的情况下, 一个常量数据中的键的数据类型会被扩大成对应的值的数据类型, 比如:
const infoWindowType = {
constant_one: 'constant_one'
}
TypeScript 推断为:
{
constant_one: string
}
造成了以下问题:
'keyAreaInfo'被 扩大(widen) 成string- 类型信息丢失
- 后面没法做值 → 类型绑定
加上as const后, 类型推断结果变成:
{
readonly constant_one: 'constant_one'
}
这里存在两个关键变化:
- 值不再是
string, 而是 **字面量类型 ****'constant_one'** - ** 属性变成
**readonly**, 不能被重新赋值 **
as const 的作用
阻止类型扩大
const a = 'hello'
// a: string
const b = 'hello' as const
// b: 'hello'
对对象:每个属性都变成字面量 + readonly
const obj = {
x: 1,
y: 'abc'
} as const
等价于:
{
readonly x: 1
readonly y: 'abc'
}
对数组:变成只读元组
const arr = [1, 2, 3] as const
推断为:
readonly [1, 2, 3]
而不是
number[]

浙公网安备 33010602011771号