I've been working on integrating EventBus with TypeScript and I'm trying to create a dynamic parameter event
in the emit
method. How can I achieve this?
interface IEventBusListener {
(...params: any[]): void
}
class EventBus {
constructor(private listeners: Record<string | symbol, IEventBusListener[]> = {}) { }
on(event: string | symbol, callback: IEventBusListener) {
if (!this.listeners[event]) {
this.listeners[event] = [];
}
this.listeners[event].push(callback);
}
off(event: string | symbol, callback: IEventBusListener) {
if (!this.listeners[event]) {
throw new Error(`Нет события: ${event.toString()}`);
}
this.listeners[event] = this.listeners[event].filter(
listener => listener !== callback
);
}
emit<T extends keyof typeof this.listeners>(event: T, ...args: any[]) {
if (!this.listeners[event]) {
throw new Event(`Нет события: ${event.toString()}`);
}
this.listeners[event].forEach(listener => {
listener(...args);
});
}
}
I was hoping for autocomplete and type checking, but unfortunately it's not functioning as expected.