I've encountered a challenge with my general handler function that processes both mouse and touch events. Despite my efforts, Typescript keeps issuing errors due to the distinction between mouseEvent
and touchEvent
.
function handleStopDrag(e: MouseEvent | TouchEvent) {
switch (e.type) {
case 'mouseup':
// Error: Argument of type 'MouseEvent | TouchEvent' is not assignable to parameter of type 'MouseEvent'.
handleMouseUp(e)
break
case 'touchcancel':
case 'touchend':
// Error: Argument of type 'MouseEvent | TouchEvent' is not assignable to parameter of type 'TouchEvent'.
handleTouchEnd(e)
break
}
}
function handleMouseUp(e: MouseEvent){ ... }
function handleTouchEnd(e: TouchEvent) { ... }
How can I effectively specify the type of event based on my conditions? Is there a more efficient way to structure my code to define the event type?