如何使用 Typescript 在 Express 中转换 req.query 参数

Mig*_*ski 16 url types request express typescript

我正在使用 TypeScript 运行 express.js 应用程序。每次我尝试处理时request.query.foo都会收到以下错误:

Argument of type 'string | ParsedQs | string[] | ParsedQs[] | undefined' is not assignable to parameter of type 'string'.
Run Code Online (Sandbox Code Playgroud)

设置:

import { Request, Response } from 'express';

function bar(request: Request, response: Response) {
  const foo: string = request.query.foo; //marked as error
}
Run Code Online (Sandbox Code Playgroud)

我在 Express 的文档中读到,您可以设置一个名为“查询解析器”的配置,当设置为“简单”时,它将始终将查询参数解析为字符串

问题是Typescript仍然认为可能会出现除字符串或未定义之外的其他内容,而我似乎找不到覆盖Request接口的方法,我只能扩展它。

Is there any way to override the Request interface? is there something wrong in my approach?

Hel*_*cos 15

您可以定义您期望的类型ReqBodyReqQuery以及 Request 类型的其他泛型。对于Response您还应该能够定义其他类型并将其作为泛型传递。不要忘记@types/express通过运行来安装npm install -D @types/express

然后您可以 为每个特定案例创建其他SomeHandlerRequest和其他ReqDictionary, ReqBody,ReqQuery和。ResBody

import { Request } from 'express'

// if you need define other response generics
// import { Request, Response } from 'express'


// This types could be exported from other file. Then you should import them
type ReqDictionary = {}
type ReqBody = { foo1 ?: string }
type ReqQuery = { foo2 ?: string }
type ResBody = { foo3 ?: string }

type SomeHandlerRequest = Request<ReqDictionary, ResBody, ReqBody, ReqQuery>

const myCustomHandler = (req: SomeHandlerRequest, res) : void => {
   const { foo1 } = req.body
   const { foo2  } = req.query

   // Your custom logic ..... for example...
   if (foo1) {
      console.log("foo1 value = ", foo1)
   }
   if (foo2) {
      console.log("foo2 value = ", foo2)
   }

   res.status(200).json({ foo3 : "it works" })
}

Run Code Online (Sandbox Code Playgroud)

  • 我最终将其转换为未知类型,然后转换为我的自定义界面类型。不确定这是好事还是坏事。 (2认同)