【发布时间】:2018-10-26 14:12:38
【问题描述】:
我想在 TypeScript 中实现一个订阅/发布类。问题是每种事件类型都有不同的数据类型,我无法弄清楚如何以静态类型的方式进行操作。这是我目前拥有的:
type EventType = "A" | "B" | "C"
interface EventPublisher {
subscribe(eventType: EventType, callback: (data: any) => void);
publish(eventType: EventType, data: any);
}
有没有办法摆脱 any 并以某种方式执行此操作,以便当我使用类型(例如 X)实例化 eventPublisher 时,subscribe 和 publish 方法的行为如下?
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
我可以这样定义接口签名:
interface EventPublisher<U extends { [key in EventType]? : U[key] }>
但无法弄清楚如何将 U[key] 与方法中的 data 类型联系起来。
【问题讨论】:
标签: typescript types