Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issue with TypeScript Generics in Apollo Server PubSub Implementation

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

You can use:

type PubSubEvents = {
  CHANGE_EVENT: string;
}

or add an explicit index signature:

interface PubSubEvents {
  CHANGE_EVENT: string;

  [event: string]: unknown;
}

References:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading