I'm implementing subscriptions in Apollo Server using TypeScript and a PubSub class for event handling. However, I've encountered an issue when trying to use a named interface for the PubSub generic type.
When using a named interface, I encounter the following error:
interface PubSubEvents {
CHANGE_EVENT: string;
}
export interface Context {
pubsub: PubSub<PubSubEvents>;
// Error: Type 'PubSubEvents' does not satisfy the constraint '{ [event: string]: unknown; }'.
}
Interestingly, the same code works fine when using an inline type definition:
export interface Context {
pubsub: PubSub<{
CHANGE_EVENT: string;
}>;
}
Why does the inline type definition work, but the named PubSubEvents interface fails? Is this a limitation of TypeScript's type system or an issue with how PubSub is implemented? How can I fix this while keeping the named interface?
You can use:
type PubSubEvents = {
CHANGE_EVENT: string;
}
or add an explicit index signature:
interface PubSubEvents {
CHANGE_EVENT: string;
[event: string]: unknown;
}
References: