我看到它在以下指令中使用:
const htmlInput: HTMLInputElement = document.getElementById('htmlInput') as HTMLInputElement;
Run Code Online (Sandbox Code Playgroud)
类型断言已经用 完成了const htmlInput: HTMLInputElement,那么为什么要as使用运算符呢?
document.getElementById()返回类型为 的对象Element。
类比类Element更通用,HTMLInputElement并且类型对象Element不具有类型对象的所有属性HTMLInputElement。
TypeScript 编译器抱怨并且不允许分配。
const htmlInput: HTMLInputElement不是类型断言,而是声明。
它是不匹配的根源。
这里是as引入类型断言的关键字。类型断言允许开发人员告诉 TS 编译器“相信我,我知道我在做什么”。
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |