【问题标题】:How to type bound the Express query param as an Array of string in Typescript如何在 Typescript 中将 Express 查询参数类型绑定为字符串数组
【发布时间】:2020-09-02 11:41:08
【问题描述】:

我正在将一组查询字符串从邮递员传递到我用 typescript 编写的 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)

来自邮递员,我正在传递这样的请求

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]);
    }
}

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

想了解,typescript 编译器如何考虑 express 查询参数的数组?

想了解,将查询参数数组提取到本地常量标识符的正确类型应该是什么,例如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)

【问题讨论】:

    标签: node.js typescript postman


    【解决方案1】:

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

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

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

    请注意,要让 typescript 编译器知道 req.query.data 是给定您的自定义 isArray 函数的数组(我假设它返回一个布尔值),您必须使用类型保护(@ 987654321@),即:

    function isArray(arr: any): arr is Array {
      return !!arr.length
    }
    

    【讨论】:

    • 您可以将嵌套的if 条件修改为if (Array.isArray(req.query.data))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 2020-12-11
    • 2016-12-15
    • 2019-02-09
    • 2020-12-27
    • 1970-01-01
    • 2021-06-27
    相关资源
    最近更新 更多