I'd like to implement a subscribe/publish class in TypeScript. The problem is that each event type has a different type for the data and I cannot figure it out how to do it in a statically typed manner. This is what I currently have:
type EventType = "A" | "B" | "C"
interface EventPublisher {
subscribe(eventType: EventType, callback: (data: any) => void);
publish(eventType: EventType, data: any);
}
Is there a way to get rid of any
and do it in a way so that when I instantiate an eventPublisher with a type, say X
, the subscribe
and publish
methods behave as follows?
interface X {
"A": number;
"B": string;
}
const publisher: EventPublisher<X> = ...;
publisher.publish("A", 1); // OK!
publisher.publish("A", "blah"); // Error, expected number by got string
I can define the interface signature like this:
interface EventPublisher<U extends { [key in EventType]? : U[key] }>
but cannot figure it out how to relate the U[key]
to the data
type in methods.