Fixing TypeScript error property does not exist on type EventTarget
When working with event listeners in TypeScript one often runs into error that a particular property does not exist on type EventTarget. While it's relatively easy to fix this error using type "any" or by typecasting the event target using "as", none of these solutions are optimal since they simply disable TypeScript's type checking, which is what we are using TypeScript for in the first place!
The better way to fix this error is to use JavaScript's instanceof operator which you can read about at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof.
Example of code that throws error:
document.querySelector('p').addEventListener('click', (event) => {
alert(event.target.textContent);
});
Error:
Property 'textContent' does not exist on type 'EventTarget'.
Solution:
document.querySelector('p').addEventListener('click', (event) => {
if (event.target instanceof Element) {
alert(event.target.textContent);
}
});