I'm currently attempting to add a generic object to a list of other generic objects within a generic class.
There seems to be an issue with the semantics, but I can't pinpoint exactly what the problem is.
type EventCallback<I, O> = (event: I) => O;
type ListenerList<K extends string | symbol | number, I, O, V extends EventCallback<I, O>> = {
[T in K]?: V[];
};
const test: ListenerList<string, string, string, (event: any) => any> = {
test : [],
};
const key = 'test';
test[key]!.push((event: string) => 'Hello ' + event); // Works fine
export default class EventProcesser<
K extends string | symbol | number,
I,
O,
V extends EventCallback<I, O>
> {
private listeners: ListenerList<K, I, O, V> = {};
public on(target: K, callback: V): void {
this.listeners[target].push(callback); // Error
}
}
If I define the type explicitly, it works, but it doesn't seem like the most elegant solution:
...
(this.listeners[target] as V[]).push(callback) // Works
...
The error message that appears states:
Property 'push' does not exist on type 'ListenerList<K, I, O, V>[K]'
.