Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error " Property 'innerText' does not exist on type 'EventTarget' "?

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
  })
}
like image 310
Yerlan Yeszhanov Avatar asked Feb 26 '19 13:02

Yerlan Yeszhanov


People also ask

Does not exist on type EventTarget?

The error "Property 'value' does not exist on type 'EventTarget'" occurs when we try to access the value property on an element that has a type of EventTarget . To solve the error, use a type assertion to type the element correctly before accessing the property. This is the index.

What is EventTarget?

The EventTarget interface is implemented by objects that can receive events and may have listeners for them. In other words, any target of events implements the three methods associated with this interface.

How do you type an event target in TypeScript?

Use a type assertion to type event. target in TypeScript, e.g. const target = event. target as HTMLInputElement . Once typed correctly, you can access any element-specific properties on the target variable.


2 Answers

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
like image 110
Osama Avatar answered Oct 14 '22 22:10

Osama


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;

like image 39
Roberto Zvjerković Avatar answered Oct 14 '22 22:10

Roberto Zvjerković