【问题标题】:Expending Request's interface seems to not work扩展请求的界面似乎不起作用
【发布时间】:2021-05-12 22:19:13
【问题描述】:

您好,我正在使用 Express 和 typescript 创建一个 api,并且我正在尝试扩展 Request 以添加用户属性。所以我在谷歌上搜索并在stackoverflow上找到了多个解释如何做到这一点的帖子,但我有一个奇怪的错误。我已经声明了我的类型,所以我可以在 vscode 上编写 req.user 并且我没有收到任何错误。 VScodre 认识到 user 是 Request 的一个属性,但是当我尝试编译时出现错误,表明我的请求对象没有 user 属性。好像我没有扩展 Request 对象

这是我的界面:

declare namespace Express{
  export interface Request{
    user: any;
  }
}

直接在express.d.ts文件中声明

我还编辑了我的 tsconfig 文件以添加

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

这是错误信息:

error TS2339: Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.

你知道是什么原因造成的吗?

【问题讨论】:

  • 你在使用 ts-node 吗?如果是,请阅读我之前在这篇文章中的回复stackoverflow.com/a/67441138/15569492。应该是类似的问题,您需要将 ts-node 文件标志设置为 true
  • 谢谢它解决了我的问题
  • 如果您觉得它有帮助,您可以考虑在该帖子中支持我的回答,让更多人能够看到并搜索它:)

标签: node.js typescript express


【解决方案1】:

可能您已经解决了问题,但对于以后的搜索,我通过以下步骤解决了问题:

使用正确的文件路径

自定义声明必须在将被编译为 JS 的文件夹中(您的 tsconfig.json 中的 'rootDir')。如果像我一样,您将根目录指定为“./src”,则声明必须位于 src 文件夹中。否则,编译器甚至不会查找该文件。

按照此目录结构创建 Express 声明文件:

Directory
|-- src
|   |-- controllers
|   |-- utils
|   |-- @types
|   |   `-- express
|   |       `-- index.d.ts
|   `-- [...] 
|-- tsconfig.json
`-- [...]

请注意,您必须将模块名称作为文件夹名称,在这种情况下,路径将为 ./src/@types/express/index.d.ts。 p>

正确设置声明

请注意,您需要指定export interface Request 而不仅仅是interface Request

此外,“声明”之外不得有其他导入,否则该声明将无法再全局访问。

如果您需要导入某些内容,请在“声明”下方执行,以免破坏声明。

你不需要做declare global,它会破坏代码。

declare namespace Express {
  // Import here any Interface you need
  import User from '../interfaces/user'

  export interface Request {
    user: User // specify your type here
  }
}

正确设置您的 tsconfig.json

在您的 tsconfig.json 文件中,插入以下选项:

{ 
  ...
  "compilerOptions": {
    // This is not necessary (my setup worked without it), but if yours doesn't it's worth a shot
    "typeRoots": ["typings", "node_modules/@types/"],
  },
  // This is important, to make the Compiler find the declaration. 
  // Without this, the compiler wouldn't be able to find your custom declaration and apply it
  "ts-node": {
    "files": true
  },
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-16
    • 2018-04-29
    • 1970-01-01
    相关资源
    最近更新 更多