Lucas
Lucas

Reputation: 14959

Typescript generic base class that defines a base callback type

I am trying to create a generic base event class:

class BaseEvent<T extends { (args?: any[]): void }> {
    addEventListener(listener: T): { (): void } {
        return () => { };
    }
}

That I can extend to specify the restrict the parameters of the callback:

class ExtraSpecialEvent
    extends BaseEvent<{ (foo: string): void }> {

}

But I cant seem to figure out the syntax. Here is a playground demonstrating my problem.

Any idea how to accomplish this?

---- UPDATE ----

As answered below by @murat-k, my generic is asking for an array... While this is what my question asks, its not what I meant. My intention was to allow 0 or more any args. The solution to my problem was to change the generic to:

class BaseEvent<T extends { (...args: any[]): void }> {
    addEventListener(listener: T): { (): void } {
        return () => { };
    }
}

Upvotes: 0

Views: 445

Answers (1)

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37604

You are declaring args as an array type. You have to pass it as a array e.g.

class ExtraSpecialEvent
    extends BaseEvent<{ (foo: string[]): void }> {

}

Upvotes: 1

Related Questions