0

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 () => { };
    }
}

1 Answer 1

1

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 }> {

}
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, yes, you are correct. I will mark this as the answer... Though it turns out I was asking the question wrong... I really wanted the ability to specify 0 or more any args... This answer sent me down the right path.
@Lucas For that you could use the ... rest parameter. See here for an example stackoverflow.com/questions/12697275/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.