【问题标题】:Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>''Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' 类型上不存在属性 'user'
【发布时间】:2023-04-03 14:30:02
【问题描述】:

请帮忙,我遇到了这个错误

src/app/middlewares/authentication.ts:16:17 - 错误 TS2339:“请求>' 类型上不存在属性“用户”。

16 req.user = 用户;

我创建了 .d.ts 文件并将其包含在 tsconfig 文件中。我仍然无法运行此代码

请查看附件截图

enter image description here

【问题讨论】:

    标签: node.js typescript express mern


    【解决方案1】:
    1. 在您的 src 目录中创建一个 types 文件夹
    2. 在 types 文件夹中使用您要扩展的包的名称创建一个文件夹。 (在这种情况下表达)。
    3. 在该文件夹中创建一个 index.d.ts 文件
     src/
       - types/
        - express/
         - index.d.ts
    
    1. 将此代码添加到索引文件中
    import express from "express";
    
    declare global {
      namespace Express {
        interface Request {
          user?: Record<string,any>
        }
      }
    }
    
    1. 记得更新你的 tsconfig.json 文件
    {
      "compilerOptions": {
        "typeRoots" : ["./src/types", "./node_modules/@types"]
      }
    }
    

    这应该可以工作

    【讨论】:

    • user 对象是否必须是可选的?我没有收到错误(到目前为止),但事实并非如此。
    • 其他答案对我不起作用,只能在 types/ 中创建一个“express”文件夹。非常感谢
    【解决方案2】:

    我之前也遇到过同样的问题。这是我解决它的方法。

    1. 我在我的项目中创建了一个名为 @types 的单独目录,以便声明合并工作。
    2. 接下来,我在其中创建了一个名为 index.d.ts 的文件,其中包含以下内容。请注意,我们需要在全局范围内声明我们自己的请求。此外,导入 express 也很重要。
    import * as express from "express"
    declare global {
        namespace Express {
            interface Request {
                user? : Record<string,any>
            }
        }
    }
    
    1. 我在 tsconfig.json 的 compilerOptions 下添加了以下行。
     "compilerOptions": {
         ...other settings,
         "typeRoots": ["@types", "node_modules/@types"],
         ...other settings
     }
    

    就是这样。它应该适用于这些更改。

    【讨论】:

    • 感谢您的回复,实际上VS代码没有显示任何错误。运行代码时出现错误
    • 仍然报错。请帮帮我
    • 嗨,@PiyushGarg,你解决过这个问题吗?我有同样的问题。
    • 请注意,您必须将typeRoots 放入compilerOptions 中,正如他在答案中所显示的那样。我把它们放在外面。感谢您的回答!
    • 在 tsconfig.json 的 typeRoots 属性关心排序。确保在 node_modules 类型之前指定本地类型!使用["./types", "node_modules/@types"] 而不是["node_modules/@types", "./types"]
    猜你喜欢
    • 1970-01-01
    • 2021-10-02
    • 2021-12-28
    • 2020-08-17
    • 2022-12-17
    • 2021-02-08
    • 1970-01-01
    • 2019-09-23
    • 2018-08-02
    相关资源
    最近更新 更多