I am in the process of migrating my project from JavaScript to TypeScript and encountering an issue with transitioning a class for managing events.
To prevent duplicate option descriptions for adding/removing event listeners, we utilize a wrapper like this:
constructor() {
this.windowResizeHandler = new MyEventHandler(
target: window,
event: 'resize',
handler: e => this.handleResize_(e),
options: {passive: true, capturing: true},
);
}
connectedCallback() {
this.windowResizeHandler.add();
}
disconnectedCallback() {
this.windowResizeHandler.remove();
}
Currently, I am unsure how to implement this in TypeScript without losing type information about events. For instance:
document.createElement('button').addEventListener('click', e => {
// Here e is MouseEvent.
});
However, if I structure my wrapper as follows:
interface EventHandlerParams {
readonly target: EventTarget;
readonly event: Event;
readonly listener: (e: Event) => void;
readonly params: AddEventListenerOptions;
}
export class EventHandler {
public constructor(params: EventHandlerParams) {}
}
Then I lose typings:
new MyEventHandler(
target: document.createElement('button'),
event: 'click',
handler: e => { /* Here e is just Event not MouseEvent */ },
options: {passive: true, capturing: true},
);
Is there a way for me to utilize event typings from lib.dom.d.ts
?