属性 'user' 不存在于类型 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'

Piy*_*arg 2 node.js express typescript mern

请帮忙,我收到此错误

src/app/middlewares/authentication.ts:16:17 - 错误 TS2339:属性 'user' 在类型 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' 上不存在。

16 req.user = 用户;

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

请找到附件截图

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

小智 31

  1. 在 src 目录中创建一个types文件夹
  2. 使用您要扩展的包的名称在 types 文件夹中创建一个文件夹。(在这种情况下是表达)。
  3. 在该文件夹中创建一个index.d.ts文件
 src/
   - types/
    - express/
     - index.d.ts
Run Code Online (Sandbox Code Playgroud)
  1. 将此代码添加到索引文件中
import express from "express";

declare global {
  namespace Express {
    interface Request {
      user?: Record<string,any>
    }
  }
}
Run Code Online (Sandbox Code Playgroud)
  1. 请记住更新您的tsconfig.json文件
{
  "compilerOptions": {
    "typeRoots" : ["./src/types", "./node_modules/@types"]
  }
}
Run Code Online (Sandbox Code Playgroud)

这应该有效

  • 其他答案对我不起作用,只能在 types/ 中创建一个“express”文件夹。多谢 (2认同)

the*_*ist 5

我之前被困在同样的问题上。这是我解决它的方法。

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

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

  • 在 tsconfig.json 的 typeRoots 属性中,关心排序。确保在 node_modules 类型之前指定本地类型!使用 `["./types", "node_modules/@types"]` 而不是 `["node_modules/@types", "./types"]` (5认同)
  • 它仍然给出错误。请帮我 (3认同)
  • 嗨,@PiyushGarg,你解决过这个问题吗?我有同样的问题。 (2认同)