Manaus Manaus - 8 days ago 4
TypeScript Question

Type casting of HTML Elements

I’m trying to get an element using


The element is a button, so if I do:

let mybutton: Element = document.querySelector(‘button.ok’);
mybutton.addEventListener('click', () => {
if (mybutton.disabled)
// TS linter returns "Property 'disabled' does not exist on Type 'Element'

So I can give my
to a HTMLButtonElement:

let mybutton: HTMLButtonElement = document.querySelector('button.ok');
// TS linter returns "Type 'Element' is not assignable to type 'HTMLButtonElement'."

So how can I manage a button and its properties in TS?


You want to explicitly cast the object, rather than trying to implicitly cast it by setting it to a variable of a predefined type:

let mybutton = <HTMLButtonElement>document.querySelector('button.ok');