I am not able to understand how generics are used in this code in nodejs module http.d.ts

huangapple go评论72阅读模式
英文:

I am not able to understand how generics are used in this code in nodejs module http.d.ts

问题

以下是翻译的内容:

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

粗体部分的含义是什么?

我考虑尝试试错的方法来看看它的含义。但是我不知道如何以及要检查什么。我认为请求扩展了IncomingMessage类型,但不知道这是如何可能的。

英文:
  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.

答案1

得分: 1

如果你有一个类似于 IncomingMessage 的类,typeof IncomingMessage 是该类的构造函数的类型(而 IncomingMessage 是该类的实例的类型)。所以这段代码表示 Request 是一个扩展了 IncomingMessage 构造函数的构造函数。(对于 Response 也是同样的情况。)

= ____ 部分表示如果没有显式提供类型参数,类型参数的默认值是什么。所以如果你写了 listener: RequestListener;,类型参数将采用它们的默认值(typeof IncomingMessagetypeof ServerResponse),但如果你写了 listener: RequestListener<X, Y>;,类型参数将分别采用 XY 的值。

英文:

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&lt;X, Y&gt;, the type parameters would take the values X and Y instead.

huangapple
  • 本文由 发表于 2023年1月3日 20:54:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/74993654.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定