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

标签 typescript types

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

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)签名:

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/

相关文章:

typescript - 如何修复 @typescript-eslint/no-misused-promises 错误

typescript - 元素隐式具有 'any' 类型,因为类型 'typeof globalThis' 没有索引签名

list - 从字符串列表 a 中导出类型 A

typescript - 是否可以基于对象属性进行动态类型?

Angular : HttpClient Service and Observable custom type

Python "in"不检查类型?

c - Clang 编译器的 C 枚举的数据类型是什么?

c++ - 在带有类型保护的模板文件中使用前向声明

Java:为什么用户必须满足扩展约束?

Scala类型约束不允许为空