通过 event.type 处理鼠标事件和触摸事件

cat*_*t-t 3 typescript

我有一个通用处理程序函数,它接受一个事件,可以是鼠标事件,也可以是触摸事件。然后它将逻辑委托给适当的函数。不过,Typescript 会抛出错误,因为显然mouseEvent !== 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) { ... }
Run Code Online (Sandbox Code Playgroud)

我如何根据上面的检查来声明事件类型是特定类型?或者是否有更好的方法来格式化我的代码以指定事件类型?

Phu*_*Ngo 5

您需要使用类型保护来使 TypeScript 将联合类型缩小MouseEvent | TouchEventMouseEventorTouchEvent类型,而不必求助于类型断言(<MouseEvent> ee as MouseEvent):

  • 使用类型谓词:
function isMouseEvent(e: MouseEvent | TouchEvent): e is MouseEvent {
    return e.type === 'mouseup'; // || e.type === 'click'...
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它

if (isMouseEvent(e)) {
    switch (e.type) {
        case 'mouseup':
            handleMouseUp(e);
            break;
} else (isTouchEvent(e)) {
    switch (e.type) {
        case 'touchcancel':
        case 'touchend':
            handleTouchEnd(e);
            break;
}
Run Code Online (Sandbox Code Playgroud)
  • instanceof
if (e instanceof MouseEvent) {
    // switch specific MouseEvent type here or inside another delegator
    handleMouseEvent(e);
} else if (e instanceof TouchEvent) {
    handleTouchEvent(e);
}
Run Code Online (Sandbox Code Playgroud)