打字稿:无法扩展快递请求

时间:2020-09-17 21:01:01

标签: typescript express

为什么Typescript不扩展Request对象?尝试使它生效,我感到无比沮丧。

在安装@ types / Express软件包后声明类型..

// global.d.ts

declare namespace Express {
  interface Request {
    user: string;
  }
}
(req, res) => {
  const user = req.user
}

Property 'user' does not exist on type 'Request'

为什么?为什么?为什么?

1 个答案:

答案 0 :(得分:2)

我在项目中创建了一个@types文件夹,并添加了以下代码:

@types/express/index.d.ts

import { Express } from "express-serve-static-core";

declare module "express-serve-static-core" {
    interface Request {
        user: {
            ... user.x here ... 
        }
    }
}

您现在可以从user扩展Request