Node.js 如何在Typescript中正确扩展请求头

Node.js 如何在Typescript中正确扩展请求头,node.js,typescript,express,types,backend,Node.js,Typescript,Express,Types,Backend,我需要req.headers中的userId,但我无法正确键入它,我该怎么做 首先,我尝试这样做: interface ISpot{ thumbnail: File, company: string, price: number, techs: string } interface IReqCustom<T> extends Request{ body: T, } export default { async s

我需要
req.headers
中的
userId
,但我无法正确键入它,我该怎么做

首先,我尝试这样做:

  interface ISpot{
    thumbnail: File,
    company: string,
    price: number,
    techs: string
  }

  interface IReqCustom<T> extends Request{
    body: T,
  }

  export default {
    async store (req: IReqCustom<ISpot>, res: Response): Promise<Response> {
      const { filename } = req.file
      const { company, techs, price } = req.body
      const { userId } = req.headers

      const user = await User.findById(userId)

      if (!user) {
        return res.status(400).json({ error: 'User doesn\'t exist' })
      }

      const spot = await Spot.create({
        user: userId,
        thumbnail: filename,
        company,
        techs: techs.split(',').map(tech => tech.trim()),
        price
      })

      return res.json(spot)
    }

}
用户创建中的错误消失,但在界面中出现另一个错误
IReqCustom

Interface 'IReqCustom<T, P>' incorrectly extends interface 'Request<ParamsDictionary, any, any, ParsedQs>'.
  Types of property 'headers' are incompatible.
    Type 'P' is not assignable to type 'IncomingHttpHeaders'.
接口“IReqCustom”错误地扩展了接口“Request”。
属性“headers”的类型不兼容。
类型“P”不可分配给类型“IncomingHttpHeaders”。

如何使这些属性识别它们各自的类型?

您需要使用
IncomingHttpHeaders
(这是由
express.Request.headers
返回的类型)并将其扩展/与自定义headers类型相交:

从“express”导入{Request,Response};
从“http”导入{IncomingHttpHeaders};
接口ISpot{
缩略图:文件,
公司名称:string,
价格:数字,
技术人员:字符串
}
接口自定义标题{
userId:string;
}
接口IReqCustom扩展请求{
主体:t主体;
标题:输入标题和标题;
}
导出常量处理程序=(请求:IReqCustom,res:Response)=>{
const{userId}=req.headers;//`userId`现在是`string`
返回res.status(200);
}

这是
express
吗?是的,我使用
从“express”导入{Request,Response}
Interface 'IReqCustom<T, P>' incorrectly extends interface 'Request<ParamsDictionary, any, any, ParsedQs>'.
  Types of property 'headers' are incompatible.
    Type 'P' is not assignable to type 'IncomingHttpHeaders'.