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

Accessing an element by index of EventTarget type in TypeScript

I am trying to access an input element on a event.target object using event.target[0] in TypeScript but I keep getting this error:

Element implicitly has an ‘any’ type because expression of type ‘0’ can’t be used to index type ‘EventTarget’.
Property ‘0’ does not exist on type ‘EventTarget’.

This is my code so far:

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

const counterDecrement = document.getElementById("counter__decrement")!;
const counterIncrement = document.getElementById("counter__increment")!;
const counterForm = document.getElementById("counter__form")!;

counterDecrement.addEventListener("click", () => {
  counterValue.innerText = (+counterValue.innerText - 1).toString();
});

counterIncrement.addEventListener("click", () => {
  counterValue.innerText = (+counterValue.innerText + 1).toString();
});

counterForm.addEventListener("submit", event => {
  event.preventDefault();
  event.target as HTMLInputElement;
  if (event.target) {
    console.log(event.target[0]);
  }
});

I get a squiggly red line under event.target[0] (line 18)

Any ideas how to resolve this?

Thanks

>Solution :

I think you can access it via counterForm’s elements and you need to set what kind of html element is counterForm

you can simply use it in this way :

const counterForm = document.getElementById("counter__form") as HTMLFormElement;
counterForm.elements[0];
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