Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type issues with wrapping around EventEmitter since v4.0.1 #222

Closed
marcelbeumer opened this issue May 11, 2020 · 4 comments
Closed

Type issues with wrapping around EventEmitter since v4.0.1 #222

marcelbeumer opened this issue May 11, 2020 · 4 comments

Comments

@marcelbeumer
Copy link

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);
  });
});
@gfmio
Copy link
Contributor

gfmio commented May 11, 2020

I've addressed a bug with that commit, just now. Will check now if the PR fixes that.

@lpinca
Copy link
Member

lpinca commented May 11, 2020

Should be fixed by #223.

@gfmio
Copy link
Contributor

gfmio commented May 11, 2020

@marcelbeumer I've tested my fix locally and it works for me. Can you verify that 4.0.3 fixes all issues for you?

@marcelbeumer
Copy link
Author

@gfmio: yes also works for me. Thanks for the super quick fix!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants