Type issues with wrapping around EventEmitter since v4.0.1
marcelbeumer opened this issue · comments
Marcel Beumer commented
Since 4.0.1 we have the the following typing issues with EventEmitter that we did not have with 4.0.0. We think it probably has something to do with e84ca51#diff-b52768974e6bc0faccb7d4b75b162c99R122.
Please see code below. Works on 4.0.0, gives type errors on 4.0.1.
Thank you!
import EventEmitter from "eventemitter3";
export enum EventFoo {
ERROR = "error",
PLAY = "play",
}
export enum EventBar {
AD_LOADED = "adLoaded",
AD_STARTED = "adStarted",
}
interface PayloadFoo {
[EventFoo.ERROR]: [{ error: Error }];
[EventFoo.PLAY]: [{}];
}
interface PayloadBar {
[EventBar.AD_LOADED]: [{}];
[EventBar.AD_STARTED]: [{}];
}
type Payload = PayloadFoo & PayloadBar;
const emitter = new EventEmitter<Payload>();
emitter.emit(EventFoo.ERROR, { error: new Error() });
emitter.on(EventFoo.ERROR, (payload) => {
console.log(payload.error);
});
type WrappedApi = {
on<K extends keyof Payload>(name: K, fn: (...args: Payload[K]) => void): void;
};
const api: WrappedApi = {
on(name, fn) {
// TYPE ERROR: Argument of type '(...args: Payload[K]) => void' is not assignable to parameter of type 'K extends EventFoo | EventBar.AD_LOADED ? Handler<Payload[K], void> : never'.ts(2345)
emitter.on(name, fn);
return emitter;
},
};
(Object.keys(EventFoo) as [keyof typeof EventFoo]).forEach((eventName) => {
api.on(EventFoo[eventName], (payload) => {
console.log(payload);
});
});
(Object.keys(EventFoo) as [keyof typeof EventFoo]).forEach((eventName) => {
// TYPE ERROR: Parameter 'payload' implicitly has an 'any' type.ts(7006)
emitter.on(EventFoo[eventName], (payload) => {
console.log(payload);
});
});
Frédérique Mittelstaedt commented
I've addressed a bug with that commit, just now. Will check now if the PR fixes that.
Luigi Pinca commented
Should be fixed by #223.
Frédérique Mittelstaedt commented
@marcelbeumer I've tested my fix locally and it works for me. Can you verify that 4.0.3 fixes all issues for you?
Marcel Beumer commented
@gfmio: yes also works for me. Thanks for the super quick fix!