#Why Does This Happen?
By default, an event target has the EventTarget
type, which lacks certain properties (such as parentNode
) that you may expect to find on a standard HTML element. For example:
elem.addEventListener('click', function (e) {
// Property 'parentNode' does not exist on type 'EventTarget'.
console.log(e.target.parentNode);
}, false);
The reason for this is that TypeScript does not assume that all event targets are HTML elements, and is, therefore, unable to automatically recognize element-specific properties. This leads to the compiler error as it cannot verify the existence of properties like parentNode
, and others on the EventTarget
type.
#How to Fix the Issue?
The parentNode
property exists on every HTML element, so you can assert Element
, HTMLElement
or a more specific type (such as HTMLInputElement
, etc.) to be the type of the event target element, which should fix this issue. You can do so in the following ways:
-
Using Type Assertion
elem.addEventListener('click', function (e) { // Property 'parentNode' does not exist on type 'EventTarget'. e.target.parentNode; // possible fixes: (e.target as Element).parentNode; (e.target as HTMLElement).parentNode; // etc. }, false);
-
Using Type Guard
elem.addEventListener('click', function (e) { // Property 'parentNode' does not exist on type 'EventTarget'. e.target.parentNode; // possible fixes: const isElem = e.target instanceof Element; // or `HTMLElement`, etc. if (isElem) { e.target.parentNode; // ... } }, false);
Using a type guard also provides type safety on runtime, where the target element can possibly be
null
or of a different type.
When specifying a type for your event target, it's important to select the most suitable type for your particular use case. You can identify the appropriate type for your HTML element by going through the list of Web API interfaces. This ensures that your TypeScript code accurately reflects the properties and methods available on the specific HTML element you're working with.
#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.