TS const 断言:让类型更精确
学习 TypeScript const 断言,用于创建只读和字面量类型。 · 难度:入门 · +15XP
const 断言的概念
as const 是 TypeScript 3.4 引入的断言方式,它告诉编译器将表达式推断为最具体的类型。它会将数组转换为只读元组,将对象属性转换为只读,并将所有值推断为字面量类型。
主要效果
| 特性 | 不使用 as const | 使用 as const |
|---|---|---|
| 数组 | string[] | readonly ['a', 'b'] |
| 对象属性 | string | number | 字面量类型 |
| 可变性 | 可修改 | 只读 |
代码示例
// 不使用 as const
const colors = ['red', 'green', 'blue'];
// 类型:string[]
// 使用 as const
const colorsConst = ['red', 'green', 'blue'] as const;
// 类型:readonly ['red', 'green', 'blue']
// 对象示例
const config = {
host: 'localhost',
port: 3000
} as const;
// config.host 类型:'localhost',而非 string
// config.port 类型:3000,而非 number
// config 所有属性均为 readonly
// 实际应用:创建枚举行为
type Direction = typeof colorsConst[number]; // 'red' | 'green' | 'blue'
function getColor(direction: Direction) {
console.log(Color: ${direction});
}
getColor('red'); // 正确
// getColor('yellow'); // 错误
练习提示
使用 as const 定义一个状态数组 ['idle', 'loading', 'success', 'error'],然后提取出状态联合类型。编写一个函数,只接受这些状态作为参数,并输出对应的消息。