#Why Does This Happen?
The checked
property exists on the HTMLInputElement
interface and not on the EventTarget
object (which is the default type for an event target). This means that when you try to access the checked
property on an event target, TypeScript will complain:
elem.addEventListener('click', function (e) {
// Property 'checked' does not exist on type 'EventTarget'.
console.log(e.target.checked);
}, false);
TypeScript complains in this instance because it cannot verify the existence of the checked
property on the EventTarget
type as this property is exclusively available on elements of type HTMLInputElement
(specifically, when you use the <input type="radio">
or <input type="checkbox">
HTML element).
#How to Fix the Issue?
To fix this issue, you can specify the correct type for the event target. Assuming that the event target is an HTML <input type="radio">
or <input type="checkbox">
element, you can fix this error in either of the following ways:
-
Using Type Assertion
elem.addEventListener('click', (e) { // Property 'checked' does not exist on type 'EventTarget'. e.target.checked; // possible fix: (e.target as HTMLInputElement).checked; }, false);
-
Using Type Guard
elem.addEventListener('click', (e) { // Property 'checked' does not exist on type 'EventTarget'. e.target.checked; // possible fix: if (e.target instanceof HTMLInputElement) { e.target.checked; } }, false);
Using a type guard also provides type safety on runtime, where the target element can possibly be
null
or of a different type.
These solutions help TypeScript understand that the event target is indeed an HTMLInputElement
, and it allows you to access the "checked
" property without triggering a type error.
#Further Reading
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.