繁体   English   中英

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

[英]Using mapped types in TypeScript to restrict method types

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

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

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

有没有一种方法可以摆脱any ,并以某种方式做到这一点,以便在我实例化类型为X的eventPublisher时, subscribepublish方法的行为如下所示?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM