I am using TypeScript 4.6.4 and given is the following function:
function foo(element: HTMLInputElement): void {
const inputElement: HTMLInputElement = element.firstChild as HTMLInputElement;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[...]
}
The error says:
This assertion is unnecessary since it does not change the type of the expression.eslint@typescript-eslint/no-unnecessary-type-assertion
The property firstChild
is of type ChildNode
, can anyone help me understand why a cast to HTMLInputElement
is unnecessary here? If I remove it, it complains that ChildNode
cannnot be assigned to HTMLInputElement
.
It is typescript-eslint that is complaining, not the Typescript compiler. If you try to run your code In the typescript playground, you'll see that it compiles without error.
The error is raised by typescript-eslint
because it reads const inputElement: HTMLInputElement
indicating that inputElement
is of type HTMLInputElement
. Therefore, typescript-eslint
is correct in saying that asserting as HTMLInputElement
doesn't change the type of inputElement
, which is already HTMLInpuElement
However, you're also correct that const inputElement: HTMLInputElement = element.firstChild
will raise a compiler error as firstChild
is indeed of type ChildNode
.
What you can do to get rid of the warning is const inputElement = element.firstChild as HTMLInputElement
. This will compile correctly and get rid of the redundant typing. inputElement
will be of type HTMLInputElement
.