TypeScript 抱怨不必要的断言



我正在使用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 的类型

属性firstChildChildNode型,谁能帮助我理解为什么这里不需要对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型。

最新更新