#Why Does This Happen?
By default, an event target has the EventTarget
type, which lacks certain properties (such as src
) that you may normally expect to find on an HTML <img>
, <script>
, <iframe>
, <audio>
, <video>
, and <embed>
element. For example:
elem.addEventListener('click', function (e) {
// Property 'src' does not exist on type 'EventTarget'.
console.log(e.target.src);
}, false);
This leads to a compiler error because TypeScript cannot verify the existence of the src
property on the EventTarget
object as this property is exclusively available on elements of type HTMLImageElement
, HTMLScriptElement
, HTMLIFrameElement
, HTMLAudioElement
, HTMLVideoElement
, and HTMLEmbedElement
.
#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 one of; HTMLImageElement
, HTMLScriptElement
, HTMLIFrameElement
, HTMLAudioElement
, HTMLVideoElement
, or HTMLEmbedElement
, you can fix this error in the following ways:
-
Using Type Assertion
elem.addEventListener('click', (e) { // Property 'src' does not exist on type 'EventTarget'. e.target.src; // possible fixes: (e.target as HTMLImageElement).src; (e.target as HTMLScriptElement).src; (e.target as HTMLIFrameElement).src; // etc. }, false);
-
Using Type Guard
elem.addEventListener('click', (e) { // Property 'src' does not exist on type 'EventTarget'. e.target.src; // possible fixes: const isMyElem = e.target instanceof HTMLImageElement; // or `HTMLScriptElement` or `HTMLIFrameElement`, etc. if (isMyElem) { e.target.src; } }, 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.