I've got a Message interface that takes a generic argument T and sets the value of T to be the type of an internal property called body:
interface Message<T> {
body: T
}
I also have an EventHandler interface that describes a generic function that takes a Message as it's sole parameter:
interface EventHandler<T> {
(event: Message<T>): void
}
Finally, I have an Integration class that has a subscribe method and a subscriptions map that both look like the following:
class Integration {
public subscriptions: new Map<string, EventHandler>()
protected subscribe<T>(eventName: string, handler: EventHandler<T>) {
this.subscriptions.set(eventName, handler)
}
}
Ultimately, I want the user to be able to define their own Integration instances like this:
interface MyEventProperties {
foo: string
}
class MyIntegration extends Integration {
constructor() {
super()
this.subscribe('My Event Name', this.myEventHandler)
}
myEventHandler(event: Message<MyEventProperties>) {
// do something
}
}
The problem is that this doesn't work. Because I don't know the generic type that ALL EventHandler functions will be getting I can't define the second generic parameter when instantiating the Map:
class Integration {
public subscriptions: new Map<string, EventHandler>()
// This errors with: Generic type 'EventHandler<T>' requires 1 type argument(s).
protected subscribe<T>(eventName: string, handler: EventHandler<T>) {
this.subscriptions.set(eventName, handler)
}
}
My question is, am I approaching this problem incorrectly or am I missing something more obvious?
EventHandlerthat doesn't have a generic type argument. Use this in yoursubscriptionscollection andEventHandler<T>in the publicsubscribemethod.Mapconstructor look like this?new Map<string, (event: any) => void>()(where it can accept any argument as a parameter)?