我正在使用TypeScript 4.6.4,给出的是以下函数:
function foo(element: HTMLInputElement): void {
const inputElement: HTMLInputElement = element.firstChild as HTMLInputElement;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[...]
}
错误说:
此断言是不必要的,因为它不会更改 expression.eslint@typescript-eslint/no-non-need-type-assertion 的类型
属性firstChild
是ChildNode
型,谁能帮助我理解为什么这里不需要对HTMLInputElement
进行投射?如果我删除它,它会抱怨ChildNode
无法分配给HTMLInputElement
.
抱怨的是Typescript-eslint 而不是 Typescript 编译器。如果您尝试在打字稿操场中运行代码,您将看到它编译时没有错误。
typescript-eslint
引发该错误,因为它读取const inputElement: HTMLInputElement
,指示inputElement
的类型为HTMLInputElement
。因此,断言as HTMLInputElement
不会改变inputElement
的类型是正确的,这已经HTMLInpuElement
但是,您也是正确的,const inputElement: HTMLInputElement = element.firstChild
会引发编译器错误firstChild
因为它确实属于ChildNode
类型。
您可以采取哪些措施来摆脱警告const inputElement = element.firstChild as HTMLInputElement
.这将正确编译并读取 redondant 类型。inputElement
将是HTMLInputElement
型。