Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'dataset' does not exist on type 'EventTarget' when I apply dataset to event.target

Tags:

typescript

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
);
like image 536
Daniel Avatar asked Nov 26 '25 07:11

Daniel


1 Answers

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
);
like image 186
Nick Avatar answered Nov 28 '25 22:11

Nick