我有一个通用处理程序函数,它接受一个事件,可以是鼠标事件,也可以是触摸事件。然后它将逻辑委托给适当的函数。不过,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)
我如何根据上面的检查来声明事件类型是特定类型?或者是否有更好的方法来格式化我的代码以指定事件类型?
您需要使用类型保护来使 TypeScript 将联合类型缩小MouseEvent | TouchEvent为MouseEventorTouchEvent类型,而不必求助于类型断言(<MouseEvent> e或e 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)
| 归档时间: |
|
| 查看次数: |
2178 次 |
| 最近记录: |