Jonathan
Jonathan

Reputation: 59

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:

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

Upvotes: 0

Views: 307

Answers (1)

Ali Sattarzadeh
Ali Sattarzadeh

Reputation: 3559

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];

Upvotes: 1

Related Questions