Property ‘checked’ does not exist on type ‘htmlelement’

The error message “property ‘checked’ does not exist on type ‘htmlelement'” commonly occurs in TypeScript when trying to access the checked property of an HTML element without specifying the specific HTML element type.

In TypeScript, the type ‘HTMLElement’ is used as a generic type to represent all HTML elements, but it does not have a ‘checked’ property. To access the ‘checked’ property, you need to specify the specific HTML element type that has this property, such as ‘HTMLInputElement’.

Here’s an example of how to fix this error:


const checkbox = document.getElementById('myCheckbox') as HTMLInputElement;
if (checkbox.checked) {
    console.log('Checkbox is checked.');
} else {
    console.log('Checkbox is not checked.');
}

In this example, we use the getElementById method to retrieve an element with the ID ‘myCheckbox’ from the DOM. By using the as HTMLInputElement syntax, we tell TypeScript to treat the returned element as an HTMLInputElement, which has the ‘checked’ property.

Now, we can safely access the ‘checked’ property of the ‘checkbox’ variable without TypeScript throwing an error.

Leave a comment