TypeScript 中的as const是什么?
const options = {url: "https://www.coderwhy.org/abc",method: "POST"
} as const
是在 TypeScript 里用 as const
把对象变成 “只读字面量类型”。我帮你一步步拆开。
1. 没有 as const
时
const options = {url: "https://www.coderwhy.org/abc",method: "POST"
}
TS 会自动推断:
{url: string;method: string;
}
也就是说:
url
被推成普通的string
类型,而不是"https://www.coderwhy.org/abc"
这个固定值。method
被推成string
类型,而不是"POST"
这个固定值。属性默认是可改的。
所以你可以这样:
options.url = "xxx"; // ✅ 允许
options.method = "GET"; // ✅ 允许
2. 加了 as const
后
const options = {url: "https://www.coderwhy.org/abc",method: "POST"
} as const
TS 会推断成:
{readonly url: "https://www.coderwhy.org/abc";readonly method: "POST";
}
也就是说:
每个属性的类型变成了 字面量类型(具体的值),而不是普通
string
。所有属性变成了 只读(readonly),不能修改。
结果:
options.url = "xxx"; // ❌ 报错:不能修改只读属性
options.method = "GET"; // ❌ 报错
3. 什么时候用 as const
?
常见场景:
定义不可变配置
避免别人修改。做字面量类型推导
比如联合类型:
const METHODS = ["GET", "POST", "PUT"] as const;
type Method = typeof METHODS[number]; // "GET" | "POST" | "PUT"
3.和函数参数搭配,保证传的是字面量类型:
function request(url: string, method: "GET" | "POST") {}
request(options.url, options.method); // ✅ 因为 method 是 "POST" 不是 string
💡 总结
as const
= 让所有属性都只读 + 让值保持字面量类型。作用是让 TS 更精确地知道你的变量的值,防止无意中改动。
🔍 一句话记住
as const = 属性全变 readonly + 值锁定为字面量类型。
这样 TypeScript 就不会帮你“泛化”成宽泛的类型,而是保留成精确值类型。