Home > database >  Typescript: Add Event Listener overloads to child class
Typescript: Add Event Listener overloads to child class

Time:05-09

I have a parent class like this:

interface A extends EventEmitter{
    on(event: "eventA", listener: () => void): this;
}

and another class like this:

interface B extends A{
    on(event: "eventB", listener: () => void): this;
}

I want to use this like this:

const foo = new B();
foo.on("eventA", listenerForA);
foo.on("eventB", listenerForB);

Changing anything in A is not possible.

Implementing it like this throws an Error: TS2415: Class 'B' incorrectly extends 'A'

PS: you also need to declare class A and class B, but for clarity I removed these.

view code in TS playground

Edit: it helps to copy the overloads from the parent class. But is there another way to do this without duplicating the overloads?

Thank you for everything that could help in any way.

CodePudding user response:

maybe like that:

// Get `on` first parameter type
type EventFrom<T extends A> = Parameters<T['on']>[0]

interface A {
    on(event: "eventA"): this;
}

interface B extends A {
    on(event: "eventB" | EventFrom<A>): this; // eventA | eventB
}

interface C extends B {
    on(event: "eventC" | EventFrom<B>): this; // eventA | eventB | eventC
}

CodePudding user response:

Inspired by the answer from Фарид Ахмедов, I have coded this, which also works for callback overloads:

interface B extends A{
    on(event: Parameters<A['on']>[0], listener: Parameters<A['on']>[1]): this;
    on(event: "eventB", listener: (bar: string) => void): this;
}

The first overload copies the previous overloads.

Using Parameters<...> you could also add all overloads for EventEmitter.emit().

  • Related