为什么在DefinitelyTyped中`http.IncomingMessage`定义为接口,而不是类?

2024-05-02

正如 Node.js 的文档所述,http.IncomingMessage 是一个类 https://nodejs.org/api/http.html#http_class_http_incomingmessage,不是一个接口。那么为什么在DefinitelyTyped中http.IncomingMessage 定义为接口 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/e2988a134ec9fa51deb43487231ac607265ba088/node/index.d.ts#L694?

现在在我的代码中我不能这样做:

import * as http from 'http';
let Request = http.IncomingMessage;

打字稿错误:

[ts] 类型“typeof“http””上不存在属性“IncomingMessage”。

我做错了什么吗?


我发现 Node.js 确实不存在扩展 APIhttp.IncomingMessage。这种方式更像是 hack 而不是正常的扩展:

http.IncomingMessage.prototype.absoluteUri = function absoluteUri(path) {
  // ...
};

I 找到了这个 https://stackoverflow.com/a/26337542/1716560回答延伸http.IncomingMessage:

var extendedRequest = {
  get userAgent() {
    this.request.headers['user-agent'];
  }
}

createServerCallback(function (req, res) {
  var request = Object.create(extendedRequest);
  request.request = req;
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么在DefinitelyTyped中`http.IncomingMessage`定义为接口,而不是类? 的相关文章

随机推荐