如何在TypeScript中正确扩展请求(Request)头

5

我需要在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)
    }

}

第34行的用户键必须是一个字符串,但它从userId接收到的值可能是string | string [] | undefined
我也尝试过这个:

interface UserHeader{
  userId: string
}

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

async store (req: IReqCustom<ISpot, UserHeader>, res: Response): Promise<Response>{}

用户分配错误已消失,但接口 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'.

我该如何使这些属性识别其各自的类型?


这是 express 吗? - gurisko
是的,我使用import { Request, Response } from 'express' - Jose Carlos Filho
1个回答

4
你需要使用 IncomingHttpHeaders(它是由express.Request.headers返回的类型)并将其与你的自定义头部类型进行扩展或交叉:
import {Request, Response} from 'express';
import {IncomingHttpHeaders} from 'http';

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

interface CustomHeaders {
  userId: string;
}

interface IReqCustom<TBody, THeader> extends Request {
  body: TBody;
  headers: IncomingHttpHeaders & THeader;
}

export const handler = (req: IReqCustom<ISpot, CustomHeaders>, res: Response) => {
  const {userId} = req.headers; // `userId` is now `string`
  return res.status(200);
}

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