I am trying to write a function to handle both mouse
and touch
events. By combining both interfaces React.TouchEvent
and React.MouseEvent
,
like:
onStart = (event: React.TouchEvent | React.MouseEvent) => {
event.persist();
console.log('event ', event);
if (event.touches) {
console.log(event.touches);
}
if (event.screenX) {
console.log(event.screenX);
}
};
The logs give me the expected output and I don't get any console error, it runs as it I expected. But I get errors on my editor:
Error:(94, 22) TS2339: Property 'screenX' does not exist on type 'MouseEvent | TouchEvent'. Property 'screenX' does not exist on type 'TouchEvent'.
and
Error:(90, 13) TS2339: Property 'touches' does not exist on type 'MouseEvent | TouchEvent'. Property 'touches' does not exist on type 'MouseEvent'.
How can I use both intefaces React.TouchEvent
and React.MouseEvent
without all this errors?
Basic Event Handling You need to use the specific React version, otherwise you get a compile error. Events supported are: AnimationEvent , ChangeEvent , ClipboardEvent , CompositionEvent , DragEvent , FocusEvent , FormEvent , KeyboardEvent , MouseEvent , PointerEvent , TouchEvent , TransitionEvent , WheelEvent .
Angular includes $event that contains the information about an event. The type of $event depends on the target event, e.g., if the target event is a native DOM element event, then it is an object. A component should define the onShow(event) method where the type of the parameter can be KeyboardEvent, MouseEvent, etc.
By checking for instanceof TouchEvent
and instanceof MouseEvent
in the condition and using the nativeEvent
property inside event
, it is possible to access each individual interface with no errors.
onStart = (event: React.TouchEvent | React.MouseEvent) => {
event.persist();
console.log('event ', event);
if (event.nativeEvent instanceof TouchEvent) {
console.log(event.nativeEvent.touches);
}
if (event.nativeEvent instanceof MouseEvent) {
console.log(event.nativeEvent.screenX);
}
};
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