Reputation: 5968
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?
Upvotes: 12
Views: 15609
Reputation: 3297
While the solution proposed by @Agney will probably work in most cases, it failed me when I was using event delegation – the property I want to access was on the child element, which was event.target
, not event.currentTarget
.
I appease the TS compiler with broadening the type of event.target
:
const handleMouseMove = (e: React.MouseEvent<SVGSVGElement>) => {
// Hey, compiler, the event target can have any of the properties of an SVG element:
const target: EventTarget & React.SVGProps<SVGSVGElement> = e.target
if (target.id) {
// ...
}
The example is using id
property instead of name
, but the principle is the same. The compiler error is gone.
Upvotes: 0
Reputation: 19194
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
*/
Upvotes: 24