[英]Using mapped types in TypeScript to restrict method types
I'd like to implement a subscribe/publish class in TypeScript. 我想在TypeScript中实现一个subscription / publish类。 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? 有没有一种方法可以摆脱
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
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. 但无法弄清楚如何在方法中将
U[key]
与data
类型相关联。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.