在我的 Node.js/Express 应用程序中,我已经有一段时间的 Headers.ts 文件包含以下内容:
type HttpHeader = 'X-My-Header' | 'X-My-Other-Header' | 'X-Another';
declare module 'express-serve-static-core' {
import * as http from 'http';
interface Request extends http.IncomingMessage, Express.Request {
header(name: HttpHeader): string | undefined;
}
}
然而,在最近的
rm -rf node_modules
之后,它曾经编译得很好。和 npm install
再次,我收到很多错误,例如error TS2339: Property 'get' does not exist on type 'Request'.
error TS2339: Property 'end' does not exist on type 'Response'.
看来核心问题是
node_modules/@types/express/index.d.ts
解决了 import * as core from "express-serve-static-core"
到我的小增强并完全跳过加载真实的东西。我不知道为什么,因为我确实有一个文件夹 node_modules/@types/express-serve-static-core
正确安装。会是什么呢?
最佳答案
从以下方面判断:
import * as http from 'http';
在您的模块声明中,您实际上并不是在编写您想要的模块“agumentation”,而是替换现有模块。
为了编写模块扩充,您需要将其编写为:
import { Request} from 'express-serve-static-core';
import * as http from 'http';
export type HttpHeader = 'X-My-Header' | 'X-My-Other-Header' | 'X-Another';
declare module 'express-serve-static-core'{
export interface Request extends http.IncomingMessage, Express.Request {
header(name: HttpHeader): string | undefined;
}
}
首先要注意的是,它应该是一个外部"file"模块(它应该有导入和导出)。
第二个要注意的是
import * as http
应该去外面的模块扩充在里面是不合法的。声明的模块现在严格用作扩充。它不会覆盖或替换现有的
express-server-static-core
模块。事实上,该模块需要存在才能进行扩充(例如,如果您拼错了模块名称,它将无法编译)。我无法从您的示例中看出为什么您的代码以前有效。也许在方式上存在差异
express-server-static-core
之前实现了声明文件。但是如果你遵循这个例子,事情应该对你有用。
关于TypeScript 模块扩充会覆盖原始模块吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40456231/