【发布时间】: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