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.
You need to add a generic type parameter for the key on the methods, and use a type query to relate the event type to the argument type.
type EventType = "A" | "B" | "C"
interface EventPublisher<T extends { [ P in EventType]? : any }> {
subscribe<E extends EventType>(eventType: E, callback: (data: T[E]) => void): void;
publish<E extends EventType>(eventType: E, data: T[E]) : void;
}
interface X {
"A": number;
"B": string;
}
const publisher: EventPublisher<X> = ...;
publisher.publish("A", 1); // OK!
publisher.publish("A", "blah"); //error
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.