TypeScript 模块扩充会覆盖原始模块吗?

标签 typescript

在我的 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/

相关文章:

javascript - typescript 显示无法设置未定义的属性,如何解决?

typescript - 从Typescript中的Promise推断返回值

angular - Typescript - 如何将错误响应转换为错误对象?

Javascript 重载函数由 Visual Studio 代码智能感知检测

javascript - 在 Typescript 中将 JSON API 响应中的字符串转换为 Typescript 中的数字

typescript 错误 TS2394 : Overload signature is not compatible with function implementation

javascript - 如何在 Angular 分量中嵌入vimeo视频?

switch 语句中的 Typescript 特定类型

typescript - d.ts 文件中的可重用方法签名

javascript - 使用: and => for the return type with a TypeScript function?有什么区别