0

I'm trying to implement an event emitter API, and I want the child class can automatically inherit the parent event interfaces, Here is my code:

class Emitter<Events = {}> {
    emit<N extends keyof Events>(name: N, ...args: Parameters<Events[N] & ((...args: any[]) => void)>) {}
}

interface AnimalEvents {
    eat: (food: string) => void
}

class Animal<Events> extends Emitter<AnimalEvents & Events>{
    constructor() {
        super()
        this.emit('eat', 'fish')
    }
}

interface CatEvents {
    miaow: (whom: string) => void
}

class Cat<Events> extends Animal<CatEvents & Events>{
    constructor() {
        super()
        this.emit('eat', 'fish')
        this.emit('miaow', 'me')
    }
}

Two problems I got: 1. Mistake in the fish of this.emit('eat', 'fish'): Argument of type '[string]' is not assignable to parameter of type 'Parameters<(AnimalEvents & Events)["eat"] & ((...args: any[]) => void)>'..

  1. I can't get type limitation of arguments for defined event type, e.g., I can only got type limitation ...args[] at this.emit('eat', HERE), but not food: string I defined in AnimalEvents.

So, what can I do to make the interface extends work, and got arguments limitation and suggestion when I input this.emit(name, ...).

Freeman Chen
  • 149
  • 1
  • 4
  • 1
    The problem is that the inside the class, the `Events` type parameter is still not known, so `Parameters` will not be able to resolve the actual parameters (what if `Events` has an `eat` method as well, we just don't know inside the class). – Titian Cernicova-Dragomir Apr 23 '19 at 14:16
  • https://stackoverflow.com/questions/55763701/extensible-strongly-typed-event-emitter-interface-in-typescript/55789081 – Titian Cernicova-Dragomir Apr 23 '19 at 14:16
  • I would close it as a duplicate of the above question, you can use the answer described there as a solution. If you want I can provide he code for your case but it is basically the same .. – Titian Cernicova-Dragomir Apr 23 '19 at 14:18
  • What's the implementation of `emit` like. To be honest I have never see such perculier event emitter API, hard to understand your intention. – hackape Apr 23 '19 at 14:23
  • Thanks very much for "Titian Cernicova-Dragomir"'s answer, I'm reading it. – Freeman Chen Apr 23 '19 at 22:08

0 Answers0