Hello fellow StackOverflowers!
I have been trying for quite some time (with more complicated code) to achieve a generic type safe callback system that where one can register a callback to some event and this callback is added to an array of listeners for the specific event type.
It works fine when I don't use an array, but just one callback per event. But typescript gets lost when I try to use an array instead to push the callback into.
enum MyEvent {
One,
Two
}
type Callback<T> = (arg: T) => void;
type CallbackTypes = {
[MyEvent.One]: number
[MyEvent.Two]: string
}
class CallbackContainer {
callbacksA: { [E in MyEvent]: Callback<CallbackTypes[E]> } = {
[MyEvent.One]: () => {},
[MyEvent.Two]: () => {}
};
callbacksB: { [E in MyEvent]: Callback<CallbackTypes[E]>[] } = {
[MyEvent.One]: [],
[MyEvent.Two]: []
};
constructor() {}
setListenerA<E extends MyEvent, C extends typeof this.callbacksA[E]>(this: CallbackContainer, event: E, callback: C) {
this.callbacksA[event] = callback; // =)
}
getListenerA<E extends MyEvent>(event: E) {
return this.callbacksA[event];
}
setListenerB<E extends MyEvent, C extends typeof this.callbacksB[E][number]>(this: CallbackContainer, event: E, callback: C) {
const callbacks = this.callbacksB[event]; // type of callbacks is still intact
callbacks.push(callback); // callbacks collapsed
}
getListenersB<E extends MyEvent>(event: E) {
return this.callbacksB[event];
}
}
const c = new CallbackContainer();
c.setListenerA(MyEvent.One, (a) => a + 1); // Types resolve fine
c.getListenerA(MyEvent.One); // Types resolve fine
c.setListenerB(MyEvent.One, (a) => a + 1); // Types resolve fine
c.getListenersB(MyEvent.One); // Types resolve fine
When pushing the callback into the array I get:
Argument of type 'Callback<number> | Callback<string>' is not assignable to parameter of type 'Callback<number> & Callback<string>'.
Type 'Callback<number>' is not assignable to type 'Callback<number> & Callback<string>'.
Type 'Callback<number>' is not assignable to type 'Callback<string>'.
Type 'string' is not assignable to type 'number'.ts(2345)
While before pushing, the compiler knows perfectly well that the type of C (the callback is):
C extends {
0: Callback<number>[];
1: Callback<string>[];
}[E][number]>
and the type of the callbacks array is:
const callbacks = {
0: Callback<number>[];
1: Callback<string>[];
}[E]
But when pushing they collapse to Callback<number> | Callback<string> and Callback<number>[] | Callback<string>[] respectively. Have I run into a limitation of the typescript compiler or am I missing something obvious? If it's a limitation, are there any workarounds? Thanks!