Borislav Hadzhiev
Thu Mar 31 2022·2 min read
Photo by Jens Kreuter
Use a type assertion to solve the "Argument of type 'HTMLElement' is not
assignable to parameter of type" error, e.g.
myFunction(element as HTMLInputElement);
. The types of the passed in argument
and the expected parameter have to be compatible.
Here are 2 examples of how the error occurs.
const element = document.getElementById('example') as HTMLElement; function example1(el: HTMLInputElement) { return el; } // ⛔️ Argument of type 'HTMLElement' is not assignable // to parameter of type 'HTMLInputElement'. example1(element); // ----------------------------------------------- function example2(el: HTMLCanvasElement) { return el; } // ⛔️ Argument of type 'HTMLElement' is not assignable // to parameter of type 'HTMLCanvasElement'. example2(element);
The reason the error occurs in the first example is - the function expects a
parameter of type HTMLInputElement
and we're passing it a parameter of type
HTMLElement
.
In the second example, the function expects a parameter of type
HTMLCanvasElement
, and we're passing it a parameter of type HTMLElement
.
We can use a type assertion to solve the error.
const element = document.getElementById('example') as HTMLElement; function example1(el: HTMLInputElement) { return el; } example1(element as HTMLInputElement); // 👈️ type assertion function example2(el: HTMLCanvasElement) { return el; } example2(element as HTMLCanvasElement); // 👈️ type assertion
Type assertions are used when we have information about the type of a value that TypeScript can't know about.
We effectively tell TypeScript that the element
variable stores a value of a
specific type and not to worry about it.
The cause of the "Argument of type 'HTMLElement' is not assignable to parameter
of type" error is - we are passing an argument of type HTMLElement
to a
function that has a parameter of a different type.
You could also use a type assertion when selecting the element.
// 👇️ use type assertion here const element = document.getElementById('example') as HTMLInputElement; function example1(el: HTMLInputElement) { return el; } example1(element);
We typed the element
variable as an HTMLInputElement
element, which is
exactly the type of parameter the example1
function expects.
If you defined the function, you can also widen the type of its expected parameter using a union type.
const element = document.getElementById('example') as HTMLElement; function example1(el: HTMLInputElement | HTMLElement) { return el; } example1(element);
Now the example function expects a parameter of type HTMLInputElement
or
HTMLElement
, so passing it an argument of type HTMLElement
satisfies the
expected parameter type.