如何使用自定义属性扩展 Express 中的请求类型

Non*_*ush 5 node.js express typescript

我正在尝试使用 typescript 在 Node.js 中设置一个自定义中间件函数,我想将解码后的 json Web 令牌存储到自定义请求属性“user”中,如下所示

  function auth(req: Request, res: Response, next: NextFunction) {

     const decodedToken = jwt.verify(token, config.get("secret"));

     req.user = decodedToken.user; 
     next();
  }
Run Code Online (Sandbox Code Playgroud)

但我在终端中不断收到编译器错误

错误 TS2339:类型“Request<ParamsDictionary,any,any,ParsedQs>”上不存在属性“user”。

我在这里找到了几个答案,建议创建一个 custom.d.ts 文件并扩展我这样做的请求类型:

namespace Express {
  interface Request {
    user?: string;
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,VS Code 很高兴,我没有得到任何 linting,我得到了正确的智能感知和自动完成,它不允许我分配一个数字,因为它知道它需要是一个字符串。所以它显然有效。但是,当我运行代码时,终端不断给出相同的错误,并坚持认为属性“用户”不存在。

我尝试重新启动 TS 服务器,但没有帮助。

我可以通过创建一个扩展请求类型的自定义接口然后使用它来使其工作,但我真的想知道如何使用原始请求类型来做到这一点。

Non*_*ush 0

经过大量谷歌搜索和使用文件夹结构和tsconfig.json文件后,我设法让它工作。我将custom.d.ts文件放入./@types/express(子文件夹必须在那里)并在tsconfig.json中设置 typeRoots ,如下所示:

compilerOptions: {
  "typeRoots": ["./@types"],
}
Run Code Online (Sandbox Code Playgroud)

我还必须在 custom.d.ts 中声明名称空间

declare namespace Express {
  interface Request {
    user: any;
  }
}
Run Code Online (Sandbox Code Playgroud)

现在编译没有错误了