typescript - 在 TypeScript 中使用映射类型来限制方法类型
问题描述
我想在 TypeScript 中实现一个订阅/发布类。问题是每种事件类型都有不同的数据类型,我无法弄清楚如何以静态类型的方式进行操作。这是我目前拥有的:
type EventType = "A" | "B" | "C"
interface EventPublisher {
subscribe(eventType: EventType, callback: (data: any) => void);
publish(eventType: EventType, data: any);
}
有没有办法摆脱any
并以某种方式做到这一点,以便当我用类型实例化 eventPublisher 时X
,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
类型相关联。
解决方案
您需要为方法上的键添加泛型类型参数,并使用类型查询将事件类型与参数类型相关联。
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