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.
Definition and Usage. The target event property returns the element that triggered the event. The target property gets the element on which the event originally occurred, opposed to the currentTarget property, which always refers to the element whose event listener triggered the event.
Obsolete This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time.
When an event is fired, the element that fires the event is known as the emitter. This element is what we call the target. So, the target property of that event object refers to the event emitter.
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
JLRishe's answer is correct, so I simply use this in my event handler:
if (event.target instanceof Element) { /*...*/ }
Using typescript, I use a custom interface that only applies to my function. Example use case.
handleChange(event: { target: HTMLInputElement; }) {
this.setState({ value: event.target.value });
}
In this case, the handleChange will receive an object with target field that is of type HTMLInputElement.
Later in my code I can use
<input type='text' value={this.state.value} onChange={this.handleChange} />
A cleaner approach would be to put the interface to a separate file.
interface HandleNameChangeInterface {
target: HTMLInputElement;
}
then later use the following function definition:
handleChange(event: HandleNameChangeInterface) {
this.setState({ value: event.target.value });
}
In my usecase, it's expressly defined that the only caller to handleChange is an HTML element type of input text.
For retrieving property you must cast target to appropriate data type:
e => console.log((e.target as Element).id)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With