I have a function that takes two different event objects one for touchscreen and the other for mouse input. TypeScript shows an error when accessing types only available to one of the events.
const desktopDragHandler = (
e: React.MouseEvent<HTMLDivElement> | React.TouchEvent<HTMLDivElement>
) => {
//depending on touch screen or mouse we have different properties
let position = { x: 0, y: 0 };
if (e.type === "touchmove") { //we have a touch event
let evt = typeof e.originalEvent === "undefined" ? e : e.originalEvent;
let touch = evt.touches[0] || evt.changedTouches[0];
position.x = touch.pageX;
position.y = touch.pageY;
} else { //we have a mouse event
position.x = e.clientX;
position.y = e.clientY;
}
}
ts shows error when accessing e.originalEvent
and e.clientX or e.clientY
. how to resolve the type error here?
CodePudding user response:
TypeScript isn't smart enough to know that e.type === "touchmove"
is the differentiator between the two types, you have to typecast it manually:
let evt = typeof (e as React.TouchEvent<HTMLDivElement>).originalEvent === "undefined" ? e : (e as React.TouchEvent<HTMLDivElement>).originalEvent;
position.x = (e as React.MouseEvent<HTMLDivElement>).clientX;
position.y = (e as React.MouseEvent<HTMLDivElement>).clientY;
Next time please create a reproducible example, I'm just guessing what's happening here.
CodePudding user response:
Try this:
const desktopDragHandler = (
e: React.MouseEvent<HTMLDivElement> | React.TouchEvent<HTMLDivElement>
) => {
//depending on touch screen or mouse we have different properties
let position = { x: 0, y: 0 };
if (e instanceof React.TouchEvent<HTMLDivElement>) { //we have a touch event
let evt = typeof e.originalEvent === "undefined" ? e : e.originalEvent;
let touch = evt.touches[0] || evt.changedTouches[0];
position.x = touch.pageX;
position.y = touch.pageY;
} else { //we have a mouse event
position.x = e.clientX;
position.y = e.clientY;
}
}