Home > Enterprise >  Why it doesn't use "<Event>" instead of "<T extends Event>"?
Why it doesn't use "<Event>" instead of "<T extends Event>"?

Time:09-30

I am just wondering to know if there is any reason the following code uses <T extends Event> instead of Event> in this line export abstract class Publisher` of the code?

import { Stan } from 'node-nats-streaming';
import { Subjects } from './subjects';

interface Event {
  subject: Subjects;
  data: any;
}

export abstract class Publisher<T extends Event> {
  abstract subject: T['subject'];
  protected client: Stan;

  constructor(client: Stan) {
    this.client = client;
  }

  publish(data: T['data']): Promise<void> {
    return new Promise((resolve, reject) => {
      this.client.publish(this.subject, JSON.stringify(data), (err) => {
        if (err) {
          return reject(err);
        }
        console.log('Event published to subject', this.subject);
        resolve();
      });
    });
  }
}

CodePudding user response:

In order to understand the difference, you need to understand what both things do.

<T extends Event>

The T is the name of the generic (this can be anything) extends Event is there so Typescript knows that you only want to allow generics that are of type Event or an implementation of it.

<Event>

Like said above a generic can be any word, like Event, you are basicly making a generic without any restrictions, and it will be typed as the type you passed it in.

  • Related