Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

typing an eventlistenner on vanilla + typescript

how can i type correctly so my event listenner has access to target.value for example in typescript + vanilla js?

I did some tests with MouseEvent, HTMLButtonElement and I can’t get a result.

const Database = {
  createDataKeys() {
    const dataKeys = Object.keys(database);

    return dataKeys.map((spot) => {
      const newBtn = document.createElement('button');

      newBtn.innerText = spot;

      newBtn.addEventListener('click', (e: MouseEvent) => {
        console.log(e.target.);
      });
      return newBtn;
    });
  }
};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’ll need to narrow it down, not every target has a value !

  newBtn.addEventListener('click', (e: MouseEvent) => {
    if (e.target instanceof HTMLInputElement) {
      console.log(e.target.value);
    }
  });

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading