我有一个通用处理程序函数,该函数接受一个可以是鼠标或触摸事件的事件。然后将逻辑委托给适当的功能。不过,打字稿会引发错误,因为显然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) { ... }
如何根据上面的检查声明事件类型是特定类型?还是有一种更好的方式格式化我的代码以指定事件类型?
答案 0 :(得分:1)
您需要使用type guard来启用TypeScript将MouseEvent | TouchEvent
联合类型缩小为MouseEvent
或TouchEvent
类型,而不必诉诸类型断言({{ 1}}或<MouseEvent> e
):
e as MouseEvent
然后像使用它
function isMouseEvent(e: MouseEvent | TouchEvent): e is MouseEvent {
return e.type === 'mouseup'; // || e.type === 'click'...
}
if (isMouseEvent(e)) {
switch (e.type) {
case 'mouseup':
handleMouseUp(e);
break;
} else (isTouchEvent(e)) {
switch (e.type) {
case 'touchcancel':
case 'touchend':
handleTouchEnd(e);
break;
}
:instanceof
答案 1 :(得分:1)
通过使用in
运算符来检查两个Typescript中都不存在的属性,从而可以用我自己的更少的精力找出其他所有问题
function dragStart(e: MouseEvent | TouchEvent) {
if ('touches' in e) {
state.initialX = e.touches[0].clientX - state.xOffset
state.initialY = e.touches[0].clientY - state.yOffset
} else {
state.initialX = e.clientX - state.xOffset
state.initialY = e.clientY - state.yOffset
}
}