Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Typescript event type for both interfaces MouseEvent and TouchEvent

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?

like image 730
Marco Daniel Avatar asked Feb 14 '19 10:02

Marco Daniel


People also ask

What is the type of event in TypeScript react?

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 .

What type is event in TypeScript angular?

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.


1 Answers

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);
    }
};
like image 168
Marco Daniel Avatar answered Nov 03 '22 01:11

Marco Daniel