6. 介绍一下 as const 断言。
约 244 字小于 1 分钟
2025-06-09
as const
是 TypeScript 中的一种类型断言,用于创建最精确、不可变的类型推断,将值标记为不可变的字面量类型。
let x = "hello" as const; // "hello"类型(精确字面量类型)
const user = {
name: "Bob",
age: 25,
} as const;
// const user: {
// readonly name: "Bob";
// readonly age: 25;
// }
const arr = [1, "two", true] as const;
// 类型为 readonly [1, "two", true]
三个特点:
- 字面量类型锁定
- 对象属性变为只读
- 数组变为元组
与const
声明的区别:
特性 | const 声明 | as const 断言 |
---|---|---|
变量不可重新赋值 | ✅ | ✅ |
属性变为只读 | ❌ | ✅ |
精确字面量类型 | ❌ | ✅ |
注意特殊情况
这种写法的变量,不会断言为只读
const user: {
name: string;
age: number;
} = {
name: "Bob",
age: 25,
} as const;
以上写法可以理解为:
let obj = {
name: "Bob",
age: 25,
} as const;
let user: {
name: string;
age: number;
};
user = obj;
obj = user;Type '{ name: string; age: number; }' is not assignable to type '{ readonly name: "Bob"; readonly age: 25; }'.
Types of property 'name' are incompatible.
Type 'string' is not assignable to type '"Bob"'.
更新日志
2025/8/24 08:17
查看所有更新日志
e7112
-1于