5
votes

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
  })
}
2
Well it doesn't. Window is possible EventTarget and it doesn't have innerText. Also Document. You need to check which EventTarget was it.Roberto Zvjerković
What console.log(e.target.nodeName) outputs?Mamun
works fine for me, but depends on what type of element was clicked: jsfiddle.net/bt0mozp3/2Pete
Try this.data.menu.title = e.target.valueMonica Acha

2 Answers

14
votes

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
1
votes

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;