【发布时间】:2019-08-09 08:52:18
【问题描述】:
我刚刚阅读了 TypeScript 3.4 RC 中新的 const 断言功能,但我没有看到它与使用 const 声明有何不同。
我使用来自announcement page 的示例对此进行了测试,该示例显然演示了使用as const(const 断言)如何防止文字类型被扩大(例如,"circle" 到string)。
// Example from official announcement
function getShapes() {
let result = [
{ kind: "circle", radius: 100 },
{ kind: "square", sideLength: 50 },
] as const;
return result;
}
for (const shape of getShapes()) {
if (shape.kind === "circle") {
console.log("Circle radius", shape.radius);
} else {
console.log("Square side length", shape.sideLength);
}
}
// Output:
// Circle radius 100
// Square side length 50
但是,当我删除 const 断言并改用 const 声明时,编译器输出或控制台输出没有任何变化,也没有引发错误。
// Altered getShapes function
function getShapes() {
const result = [
{ kind: "circle", radius: 100 },
{ kind: "square", sideLength: 50 },
];
return result;
}
那么有什么区别呢?公告页面列出了使用const断言的三个理由:
&项目符号;不应扩大该表达式中的文字类型(例如,不要从“hello”变为字符串)
&子弹;对象字面量获取只读属性
&子弹;数组字面量变成只读元组
但它没有解释断言和声明有何不同。
【问题讨论】:
-
您的示例没有像公告示例那样使用
Shape类型。如果您将其包含在自己的示例中,您会看到差异。 -
@Aaron 我不确定你的意思。我更改的示例与最初的示例完全相同,但更改了
const使用。 -
将返回类型注释添加到
getShapes(),你会看到TS给你的“可怕的错误信息”(公告措辞)没有 const断言。