我正在使用TypeScript和PubSub类在Apollo Server中实现订阅,用于事件处理。然而,在尝试为PubSub泛型类型使用命名接口时,我遇到了一个问题。
使用命名接口时,我遇到以下错误:
interface PubSubEvents {
CHANGE_EVENT: string;
}
export interface Context {
pubsub: PubSub<PubSubEvents>;
// Error: Type 'PubSubEvents' does not satisfy the constraint '{ [event: string]: unknown; }'.
}
有趣的是,当使用内联类型定义时,相同的代码工作得很好:
export interface Context {
pubsub: PubSub<{
CHANGE_EVENT: string;
}>;
}
为什么内联类型定义有效,但命名的PubSubEvents接口失败?这是TypeScript类型系统的限制,还是PubSub实现方式的问题?如何在保留命名接口的同时修复此问题?