13

I have an error:

Property 'innerText' does not exist on type 'EventTarget'.

I'm trying to add event listener and get value from element. Everything works fine but this error shows up in console .

public componentDidMount() {
  const element = document.querySelector(".mdc-list")
  element.addEventListener("click", (e) => {
    this.data.menu.title = e.target.innerText
  })
}
Pete
  • 57,112
  • 28
  • 117
  • 166
Yerlan Yeszhanov
  • 2,149
  • 12
  • 37
  • 67

2 Answers2

33

It is a TypeScript issue, cast the event.target to it’ type to tell TypeScript that it has the property you set for it.

const input = event.target as HTMLElement;
this.data.menu.title=input.innerText
Osama
  • 2,912
  • 1
  • 12
  • 15
1

You can either make a type guard to narrow down the event target type.

Or just cast the event target to whichever element you're getting as a target:

this.data.menu.title = <HTMLInputElement>(e.target).innerText;

Roberto Zvjerković
  • 9,657
  • 4
  • 26
  • 47