TypeScript 版本 1.7.6 是否支持 touchevents 的 dts 库?

Does TypeScript version 1.7.6 support dts lib for touchevents?

我找到了以下 link: Does TypeScript support TouchEvent?

它解决了我遇到的问题。根据文章顶部的 post,它指出 TypeScript 1.5.3 将 HTML 触摸事件的声明添加到 lib.d.ts。

TypeScript 1.7.6 版是否支持这些触摸事件?我在 Visual Studio 2015 中收到一条错误消息:属性 'changedTouches' 在类型 'Event' 上不存在。

lib.d.ts 需要什么才能让它工作。我已经尝试使用 NuGet 下载最新的 jquery.TypeScript.DefinitelyTyped version="2.8.8",但这似乎不起作用。

有什么建议吗?

更新 我验证了来自 NuGet 的 jquery d.ts 文件与 https://github.com/DefinitelyTyped/DefinitelyTyped.

上的文件相同

代码段

$('#previewEvent').on('mousedown touchstart', function(e) {
 var original = e.originalEvent;
 if (original.changedTouches && CheckMobile.isTouch_p) {
     const touchobj = original.changedTouches[0];
     swipedir = 'none';
     distX = 0;
     distY = 0;
     startX = touchobj.pageX;
     startY = touchobj.pageY;
     // record time when finger first makes contact with surface
     startTime = new Date().getTime();
     return !0;
} else if (!CheckMobile.isTouch_p) {
     return !0;
 }
 return !0;
});

更新 我最初认为 lib.d.ts 指的是 jQuery。我错了,它是随TypeScript一起安装的库之一。

我更新了库,还是一样的错误。 lib.d.ts 文件似乎有触摸定义,这是朝着正确方向迈出的一步。

问题似乎是 jQuery BaseJQueryEventObject 接口和 TypeScript TouchEvent 接口之间的不兼容。我还不确定如何解决这个问题,但我可以通过声明 var original: any = e.originalEvent 来消除错误,这掩盖了不兼容性。

关于如何正确解决这个问题的任何想法?我猜它需要第三个 d.ts 文件来解决接口问题。

谢谢...

在你的处理函数中 e 的类型是 JQueryEventObject

originalEvent 来自 BaseJQueryEventObject,类型为 EventEvent 就是我们回到 lib.d.ts 的地方。到目前为止一切正常。

因为 Event 是许多派生事件类型(如 GamepadEventMutationEvent 等)的基本接口,它只包含所有这些事件的共享数据字段类型。这就是您无法访问 changedTouches 的原因,因为就 TypeScript 编译器而言,它不是 TouchEvent.

我将使用 TypeScript 1.4 中引入的一项名为 type guards 的功能来解决这个问题。

A common pattern in JavaScript is to use typeof or instanceof to examine the type of an expression at runtime. TypeScript now understands these conditions and will change type inference accordingly when used in an if block.

因为您为 mousedowntouchstart 事件指定了相同的处理程序,所以 e.originalEvent 可以是 MouseEventTouchEvent

所以你必须处理这两种情况:

$("#previewEvent").on("mousedown touchstart", function(e) {
    var original = e.originalEvent;
    if(original instanceof TouchEvent) {
        // Handling the touchstart event
    } else if(original instanceof MouseEvent) {
        // Handling the mousedown event
    }
});

好消息是,正如引用所说,您将在 if 语句的每个分支中获得适当的自动完成支持。