I am trying to set an input element's value
property using Typescript. To do so, I have to specify that the event target is HTMLInputElement
.
I have tried two methods:
First method
onClick={(e: React.MouseEvent) => {
const target = e.target as HTMLInputElement;
target.value = "";
}}
Second method
onClick={(e: React.MouseEvent<HTMLInputElement>) => {
e.target.value = "";
}}
The first method is working fine but the second is raising the following TS error:
TS2339: Property 'value' does not exist on type 'EventTarget'.
How do these two methods differ and why is the second failing?
CodePudding user response:
It doesn't inherit from Element because not all event targets are elements.
From MDN:
Element, document, and window are the most common event targets, but other objects can be event targets too, for example XMLHttpRequest, AudioNode, AudioContext, and others.
Even the KeyboardEvent
you're trying to use can occur on a DOM element or on the window object (and theoretically on other things), so right there it wouldn't make sense for evt.target to be defined as an Element.
If it is an event on a DOM element, then I would say that you can safely assume evt.target. is an Element. I don't think this is an matter of cross-browser behavior. Merely that EventTarget is a more abstract interface than Element.
Further reading: https://github.com/Microsoft/TypeScript/issues/29540
CodePudding user response:
Use like this:
const onClick = ({ currentTarget: { files } }: React.ChangeEvent<HTMLInputElement>) => {
const filesArray = Array.from(files)
}
You will get your files in this array if you are taking multiple files.