我想在 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)签名:
interface EventPublisher<U extends { [key in EventType]? : U[key] }>
但无法弄清楚如何将 U[key]
与方法中的 data
类型相关联。
最佳答案
您需要为方法上的键添加泛型类型参数,并使用类型查询将事件类型与参数类型相关联。
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
关于typescript - 在 TypeScript 中使用映射类型来限制方法类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50372304/