类型“Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>”上不存在属性“user”。

13

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

src/app/middlewares/authentication.ts:16:17 - error TS2339: Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.

16             req.user = user;

我已经创建了 .d.ts 文件并将其包含在 tsconfig 文件中,但我仍然无法运行此代码。
请查看附加的截图。 enter image description here enter image description here enter image description here
6个回答

31
在你的src目录中创建一个名为types的文件夹,在types文件夹中创建一个名为要扩展的包的名称(在这种情况下是express)的文件夹,然后在该文件夹中创建一个名为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 对象是否需要是可选的?目前为止,如果不是可选的,我没有收到错误信息。 - tim.rohrer
2
其他答案对我没用,只有在 types/ 文件夹中创建一个 "express" 文件夹才有效。非常感谢。 - Benjamin Piette
当我尝试在我的passport.ts文件中使用它时,它显示“Express未定义”。 - PirateApp
解决方案非常有帮助。它也解决了我遇到的问题。 - damisparks
解决方案很有帮助。它也解决了我遇到的问题。 - undefined

7

我之前也遇到了同样的问题,以下是我是如何解决的。

  1. 我在我的项目中创建了一个名为 @types 的独立目录,以使声明合并工作。
  2. 接下来,在其中创建了一个名为 index.d.ts 的文件,并添加了以下内容。请注意,我们需要在全局范围内声明自己的请求。同时,导入 express 也很重要。
import * as express from "express"
declare global {
    namespace Express {
        interface Request {
            user? : Record<string,any>
        }
    }
}

我在tsconfig.json文件的compilerOptions下添加了以下行。
 "compilerOptions": {
     ...other settings,
     "typeRoots": ["@types", "node_modules/@types"],
     ...other settings
 }

就这些了。在这些更改后它应该可以工作。


1
谢谢回复,实际上 VS Code 没有显示任何错误。当我运行代码时才会出现错误。 - Piyush Garg
3
它仍然出现错误。请帮助我。 - Piyush Garg
2
嗨,@PiyushGarg,你解决了这个问题吗?我也遇到了同样的问题。 - Tony
请注意,您必须像他在答案中展示的那样将typeRoots放在compilerOptions内部。我之前是将它们放在外面的。感谢这个答案! - Gabriel Arghire
5
在tsconfig.json文件的typeRoots属性中,顺序很重要。确保在node_modules类型之前指定本地类型!使用["./types", "node_modules/@types"]而不是["node_modules/@types", "./types"] - Marshmellow1328
为了我的设置,我需要将自定义的“types”移动到我的“src”文件夹中,而不是项目根目录。 - tim.rohrer

2
另一种方法:
import { NextFunction, Request, Response } from 'express';

interface IDecode {
    address: string,
    role: string,
    iat: number,
    exp: number
  };

 interface RequestWithUserRole extends Request {
    user?: IDecode,
}


 const parseToken = (secret: string) => 
  async (req: RequestWithUserRole, res: Response, next: NextFunction) => {
    try{
      const token  = req.headers?.authorization?.split(' ')[1];
      // console.log(req.headers?.authorization);
      if (!token) {
        return res.status(403).json({message: 'Token not  found'})
      }
      const decodedData = <IDecode> jwt.verify(token, secret);
      req.user = decodedData;
      // console.log(decodedData);
      return next();
    }
    catch(e) {
      return res.status(500).json({e})  
    }
};

你的回答可以更好地添加更多关于代码的作用以及如何帮助问题提出者的信息。 - Tyler2P

1
只需安装 Passport.js 的类型即可:
npm install -D @types/passport

这个成功了!!! - undefined

1
这些是我想在请求对象中使用的变量。在你的`/src/types/express/index.d.ts`文件中,你应该放置以下内容:
```typescript export {}
declare global { namespace Express { export interface Request { idUser?: string email?: string username?: string // 在req对象中使用的其他变量 } }
} ```
在你的`tsconfig.json`文件中:
```json { "compilerOptions": { // 其他设置 "typeRoots": ["./src/types", "./node_modules/@types"] // 非常重要,将你的路径文件放在第一位,否则它将无法工作 // 其他设置 } } ```
这对你也应该有效。祝你好运!

0
如果您正在进行快速原型设计或遵循教程,则可以快速浏览以下内容:(req as any).user
注:不要在真正的生产应用程序中使用此方法,因为它会使您的代码变得混乱且不具有可扩展性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接