如何在 Typescript 中将 Express 查询参数绑定为字符串数组

Sri*_*san 6 node.js typescript postman

我将一组查询字符串从邮递员传递到用打字稿编写的 Nodejs 服务器。在我的后端代码中,Typescript 编译器无法理解在快速请求对象的查询字段中发送的查询参数的类型。它一直抱怨下面的错误。

Element implicitly has an 'any' type because the expression of type '0' can't be used to index type 'string | ParsedQs | string[] | ParsedQs[]'.
  Property '0' does not exist on type 'string | ParsedQs | string[] | ParsedQs[]'.ts(7053)
Run Code Online (Sandbox Code Playgroud)

我从邮递员那里传递请求是这样的

http://localhost:56368/api/v1/admin/GetUserWorkingHrs?data[]=Alok,Singapore/ITPL/Building1/F1/Z1,booking,create

我的后端如下。

getUserWorkingHrs = async (req: Request, res: Response) => {
    if(req.query.data){
      console.log(isArray(req.query.data), 'length of Array is :', req.query.data.length);
      console.log('TypeScript Error >> Property 0 does not exist on type string | ParsedQs | string[] | ParsedQs[].ts(7053)', req.query.data[0]);
    }
}
Run Code Online (Sandbox Code Playgroud)

对于我对 isArray(req.query.param) 的检查,我得到true并且数组的长度返回1,但是如果我在 req.query.data 上使用 forEach 循环,编译器会报告错误“找不到属性 forEach for一个字符串”,如果我将 req.query.data 视为字符串并应用 split 函数,我也会收到错误。

想了解,打字稿编译器如何考虑快速查询参数的数组?

想要了解,将查询参数数组提取到本地常量标识符的正确类型应该是什么const qry:any[] = req.query.data;对于这项作业,我遇到以下错误。

'qry' is declared but its value is never read.ts(6133)
Type 'string | ParsedQs | string[] | ParsedQs[]' is not assignable to type 'any[]'.
  Type 'string' is not assignable to type 'any[]'.ts(2322)
Run Code Online (Sandbox Code Playgroud)

Hen*_*nke 3

req.query.data是 类型string | ParsedQs | string[] | ParsedQs[],因此它可以是数组,也可以不是数组string | ParsedQs

如果它是 a ParsedQs,您的代码将会崩溃,因为您试图访问[0]该对象的属性,该属性不存在,因为它不是数组。因此,您的代码流程必须更改才能正常工作,如下所示:

getUserWorkingHrs = async (req: Request, res: Response) => {
    if(req.query.data){
      if (isArray(req.query.data)) {
         doSomethingWith(req.query.data[0]);
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,为了让打字稿编译器知道 req.query.data 是一个给定您的自定义isArray函数的数组(我假设返回一个布尔值),您必须使用类型保护来注释该函数(https://www.typescriptlang .org/docs/handbook/advanced-types.html),即:

function isArray(arr: any): arr is Array {
  return !!arr.length
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以将嵌套的“if”条件修改为“if (Array.isArray(req.query.data))”。 (4认同)