【问题标题】:Typescript extends express request object and export itTypescript 扩展了 express 请求对象并将其导出
【发布时间】:2021-06-05 00:11:53
【问题描述】:

使用打字稿,我希望从 express 扩展 Request 对象以添加我的自定义字段。

this source 之后,我创建了一个包含以下内容的@types/express/index.d.ts 文件:

import { MyClass } from "../../src/MyClass";

declare global {
    namespace Express {
        export interface Request {
            myField?: MyClass;
        }
    }
}

并添加 tsconfig.json :

"typeRoots": [
  "@types",
  "./node_modules/@types"
],

它工作正常。 但我正在开发一个自制的 npm 模块,我将它安装在另一个节点应用程序上。

我想“导出”这个新的请求类型,以便应用程序能够使用它

import { MyClass } from 'mymodule';

app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
    req.myField = new MyClass(); // <= Typescript doesn't know myField in Request
});

【问题讨论】:

    标签: node.js typescript express npm


    【解决方案1】:

    你的类型定义应该是这样的:

    import { MyClass } from "../../src/MyClass";
    
    declare namespace Express {
      export interface Request {
        myField?: MyClass;
      }
    }
    

    【讨论】:

    • 我做到了,但这还不够。我找到的一个解决方案是导出我的包上的@types 文件夹:"files": [/*...*/, "@types/**/*"] 然后将"typeRoots": ["@types", "./node_modules/mymodule/@types"], 添加到应用程序的 tsconfig.json 中。但这不是很方便,因为我的包的用户必须这样做。我可以使用更自动的方式吗?
    猜你喜欢
    • 2021-01-12
    • 2021-01-07
    • 2017-02-26
    • 2019-05-30
    • 2015-11-05
    • 2016-09-19
    • 2021-05-30
    • 2021-07-08
    • 2017-11-23
    相关资源
    最近更新 更多