typescript - TypeScript const 断言和声明之间有什么区别?
问题描述
我刚刚阅读了const
TypeScript 3.4 RC 中的新断言功能,但我没有看到它与使用const
声明有何不同。
我使用公告页面中的一个示例对此进行了测试,该示例显然演示了 using as const
( const
assertion) 如何防止文字类型被扩大(例如,"circle"
to 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”变为字符串)
• 对象文字获得只读属性
• 数组文字变为只读元组
但它没有解释断言和声明的不同之处。
解决方案
const
声明是声明后不能更改的变量声明。这是 Typescript 支持的 Javascript 功能。
const x ={ n: 10} ;
x.n = 11; //ok
x= { n:11}; // error
const
assertion 是一种类型断言,它对断言目标具有您所描述的影响。
const x ={ n: 10} as const;
x. n = 11; // error n is readonly
推荐阅读
- ios - 如何从 SKScene 回到 UIViewController (MenuVC)?
- java - 如何逐行比较两个文件,然后逐字比较。我们还需要在输出中突出显示不匹配的单词
- c# - 执行从 C# 到 EuroTruck 的密钥输出不起作用(PostMessage、user32.dll)
- statistics - 为什么 Grafana 不向我显示正确的计数?
- oracle - PL/SQL代码出错,无法理解代码中的错误和错误
- c# - C#中字符串解析的正则表达式
- java - 添加第二条记录时休眠 OneToMany 错误
- python - 如何复制工作簿末尾而不是开头的工作表?
- ios - 我应该如何在 RxSwift Singles 中正确使用保护语句?
- http - Delphi ServerSocket 对客户端的响应