How do I make TypeScript happy regarding this error:
Property 'dataset' does not exist on type 'EventTarget'
I get it when I try to implement this code snippet:
document.addEventListener(
"click",
(event) => {
event.preventDefault();
if (event !== null && event.target !== null) {
const element = event.target as Element;
if (element.matches(".dropdown-item.city")) {
const cityName = event.target.dataset.value;
console.log("City =", cityName);
dropdown.classList.toggle("active");
}
}
},
false
);
One option rather than asserting the type is to check that the element is the right type in your conditional. In this case, I believe you want to make sure it's an instanceof HTMLElement.
document.addEventListener(
"click",
(event) => {
event.preventDefault();
if (event !== null && event.target instanceof HTMLElement) {
const element = event.target;
if (element.matches(".dropdown-item.city")) {
const cityName = element.dataset.value;
console.log("City =", cityName);
dropdown.classList.toggle("active");
}
}
},
false
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With