在TypeScript中使用映射类型来限制方法类型

时间:2018-05-16 13:30:37

标签: typescript types

我想在TypeScript中实现一个subscribe / publish类。问题是每个事件类型都有不同的数据类型,我无法弄清楚如何以静态类型的方式执行此操作。这就是我目前所拥有的:

type EventType = "A" | "B" | "C"

interface EventPublisher {  
    subscribe(eventType: EventType, callback: (data: any) => void);
    publish(eventType: EventType, data: any);
}

有没有办法摆脱any并以某种方式执行此操作,以便在我实例化具有类型的eventPublisher时,例如Xsubscribe和{{1方法表现如下?

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]类型相关联。

1 个答案:

答案 0 :(得分:3)

您需要为方法上的键添加泛型类型参数,并使用类型查询将事件类型与参数类型相关联。

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
相关问题