Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'name' does not exist on type 'EventTarget' - React + TypeScript

This is my code:

<Button
  disabled={filter === 'Active'}
  size='md'
  color='primary'
  name='Active' // complete = false
  onClick={this.handleFilterClick}
>
  Active
</Button>

On my function handler I get error on the event:

handleFilterClick = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
    // continue here
     const { name } = e.target;

It says:

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

I also tried:

(e:  React.MouseEvent<HTMLInputElement, MouseEvent> &  React.MouseEvent<HTMLButtonElement, MouseEvent>) 

What is the event type for button? In JavaScript, this works, it can accept name but I don't know why not typescript?

like image 215
gpbaculio Avatar asked Mar 28 '19 02:03

gpbaculio


People also ask

How do you solve property value does not exist on type EventTarget?

js error "Property 'value' does not exist on type EventTarget" occurs when the type of the event parameter is incorrect. To solve the error, type the event as React. ChangeEvent<HTMLInputElement> . You can then access the value as event.

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.


1 Answers

event.target is the element from which element is dispatched, which necessarily doesn't have to be the HTMLButtonElement defined in the event.

However, if you use event.currentTarget, you will see that this error goes away:

const { name } = event.currentTarget;

If you have to use event.target itself, you would have to cast the object:

const { name } = event.target as HTMLButtonElement;

From the typings:

/**
  * currentTarget - a reference to the element on which the event listener is registered.
  *
  * target - a reference to the element from which the event was originally dispatched.
  * This might be a child element to the element on which the event listener is registered.
  * If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/12239
*/
like image 95
Agney Avatar answered Sep 22 '22 20:09

Agney