Skip to content

Instantly share code, notes, and snippets.

@joaomilho
Last active December 6, 2020 00:29
Show Gist options
  • Save joaomilho/06513f694889f2a249be3445f1018ea7 to your computer and use it in GitHub Desktop.
Save joaomilho/06513f694889f2a249be3445f1018ea7 to your computer and use it in GitHub Desktop.
Type safe event handlers
type Events = {
start: [];
progress: [number];
complete: [string, boolean];
};
class Uploader {
listeners: {
[key in keyof Events]: ((...params: Events[key]) => void)[];
};
constructor() {
this.listeners = {
start: [],
complete: [],
progress: [],
};
}
addEventListener<Type extends keyof Events>(
type: Type,
listener: (...params: Events[Type]) => void
) {
this.listeners[type].push(listener);
}
onStart() {
this.listeners.start.forEach((listener) => {
listener();
});
}
onProgress() {
this.listeners.progress.forEach((listener) => {
listener(1);
});
}
onComplete() {
this.listeners.complete.forEach((listener) => {
listener("ok", true);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment