Skip to content

Instantly share code, notes, and snippets.

@JTRNS
Created September 30, 2024 10:12
Show Gist options
  • Save JTRNS/0496b0f78d11407b825417a4d17fe090 to your computer and use it in GitHub Desktop.
Save JTRNS/0496b0f78d11407b825417a4d17fe090 to your computer and use it in GitHub Desktop.
CustomEventTarget, like EventTarget but with typed custom events.
type CustomEventMap<T> = {
[key in keyof T]: CustomEvent | Event;
};
interface CustomEventListener<M, K extends keyof M> {
(evt: M[K]): void;
}
interface CustomEventListenerObject<
M,
K extends keyof M,
> {
handleEvent(evt: M[K]): void;
}
type CustomEventListenerOrEventListenerObject<
M,
K extends keyof M,
> =
| CustomEventListener<M, K>
| CustomEventListenerObject<M, K>;
export class CustomEventTarget<M extends CustomEventMap<M>>
extends EventTarget {
override addEventListener<K extends keyof M & string>(
type: K,
listener: CustomEventListenerOrEventListenerObject<M, K> | null,
options?: boolean | AddEventListenerOptions,
): void {
super.addEventListener(
type,
listener as EventListenerOrEventListenerObject,
options,
);
}
dispatchCustomEvent(event: M[keyof M]): boolean {
return super.dispatchEvent(event);
}
override removeEventListener<K extends keyof M & string>(
type: K,
callback: CustomEventListenerOrEventListenerObject<M, K> | null,
options?: EventListenerOptions | boolean,
): void {
super.removeEventListener(
type,
callback as EventListenerOrEventListenerObject,
options,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment