2

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
);
1
  • Does const element = event.target as HTMLElement; work? (you would then have to do const cityName = element.dataset.value;)
    – Nick
    May 20, 2021 at 0:43

2 Answers 2

3

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
);
0

Let's start by creating a custom dataset generic type that extends the native dataset type.

export type DatasetInjector<T, D extends DOMStringMap> = T & {
  dataset: D;
};

Now to showcase above custom generic let's assume I've two inputs (input, textaera) and each have custom attribute inputId. This is to identify which the input called the on change handler when we entered the password or confirm password.

const Input = () => {
  const [value, setValue] = React.useState({
    password: '',
    confirmPassword: '',
  });

  const changeHandler: ChangeEventHandler<
    DatasetInjector<HTMLInputElement, { inputId: string }>
  > = (e) => {
    setValue((prevState) => ({
      ...prevState,
      [e.target.dataset.inputId]: e.target.value,
    }));
  };

  const textareaChangeHandler: ChangeEventHandler<
    DatasetInjector<HTMLTextAreaElement, { inputId: string }>
    > = (e) => {
    setValue((prevState) => ({
      ...prevState,
      [e.target.dataset.inputId]: e.target.value,
    }));
  };

  return (
    <>
      <input
        data-input-id='password'
        onChange={changeHandler}
        value={value.password}
      />
      <textarea
        data-input-id='confirmPassword'
        onChange={textareaChangeHandler}
        value={value.confirmPassword}
      />
    </>
  );
};

For more info see my article here Reference link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.