UPDATE
TypeScript 1.5.3 added declarations for HTML Touch events to lib.d.ts
I can see that it supports UIEvent, but it does not seem to have interfaces for touch events.
This code indicates that "TouchEvent does not exist in the current scope."
class Touchy {
private _element:Element;
constructor(theElement:Element) {
this._element = theElement;
theElement.addEventListener("touchstart", (theTouchEvent:TouchEvent) => alert("touchy"));
}
}
I can use UIEvent, but not TouchEvent. How would I handle TouchEvent's with TypeScript? Thanks.
Since TypeScript 3.7.7, TouchEvent is supported in lib.dom.d, see TouchEvent It's still worth going to the Touch Events W3C specification to more fully understand the TypeScript declarations.
Original Answer: thank you for the advice. I went to the Touch Events Specification W3C Working Draft 05 May 2011 and created a set of ambient declarations from that. There is a more recent candidate recommendation, but this is what I think is actually implemented in most browsers. This seems to work well.
PS: the declare var TouchEvent at the bottom is not part of the w3c draft. It is an adaptation of the same code for UIEvent that is part of the standard interfaces shipped with TypeScript.
interface Touch {
identifier:number;
target:EventTarget;
screenX:number;
screenY:number;
clientX:number;
clientY:number;
pageX:number;
pageY:number;
};
interface TouchList {
length:number;
item (index:number):Touch;
identifiedTouch(identifier:number):Touch;
};
interface TouchEvent extends UIEvent {
touches:TouchList;
targetTouches:TouchList;
changedTouches:TouchList;
altKey:bool;
metaKey:bool;
ctrlKey:bool;
shiftKey:bool;
initTouchEvent (type:string, canBubble:bool, cancelable:bool, view:AbstractView, detail:number, ctrlKey:bool, altKey:bool, shiftKey:bool, metaKey:bool, touches:TouchList, targetTouches:TouchList, changedTouches:TouchList);
};
declare var TouchEvent: {
prototype: TouchEvent;
new(): TouchEvent;
}
You have several options here:
First option: Extend UIEvent to have the members you'd expect on a TouchEvent (and only use them in touch event listeners):
interface UIEvent {
targetTouches: { pageX: number; pageY: number; }[];
// etc...
}
Second option: Define your own TouchEvent interface and add a type assertion when binding the event
interface TouchEvent {
(event: TouchEventArgs): void;
}
interface TouchEventArgs {
targetTouches: { pageX: number; pageY: number; }[];
// etc
}
theElement.addEventListener("touchstart", <UIEvent>((theTouchEvent:TouchEvent) => alert("touchy")));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With