Home > Back-end >  I am not able to understand how generics are used in this code in nodejs module http.d.ts
I am not able to understand how generics are used in this code in nodejs module http.d.ts

Time:01-04

  type RequestListener<
        Request extends **typeof IncomingMessage = typeof IncomingMessage**,
        Response extends **typeof ServerResponse = typeof ServerResponse**,
    > = (req: InstanceType<Request>, res: InstanceType<Response> & { req: InstanceType<Request> }) => void;

what is the meaning of the bold part here

I thought of trying hit and try method to see what it means. But I don't know how and what to check here. I think that request extends the IncomingMessage type, but don't know how is that possible.

CodePudding user response:

If you have a class like IncomingMessage, typeof IncomingMessage is the type of the constructor function of that class (whereas IncomingMessage is the type of instances of the class). So that code is saying that Request is a constructor function that extends the IncomingMessage constructor function. (And the same sort of thing for Response.)

The = ____ part says what the default for the type parameter is if none is provided explicitly. So if you did listener: RequestListener;, the type parameters would take their default values (typeof IncomingMessage and typeof ServerResponse), but if you did listener: RequestListener<X, Y>, the type parameters would take the values X and Y instead.

  • Related