Node.js 如何在Typescript中将Express查询参数作为字符串数组键入
我正在将一个查询字符串数组从postman传递到用typescript编写的Nodejs服务器。 在我的后端代码中,Typescript编译器无法理解在express请求对象的查询字段中发送的查询参数的类型。它不断地抱怨下面的错误Node.js 如何在Typescript中将Express查询参数作为字符串数组键入,node.js,typescript,postman,Node.js,Typescript,Postman,我正在将一个查询字符串数组从postman传递到用typescript编写的Nodejs服务器。 在我的后端代码中,Typescript编译器无法理解在express请求对象的查询字段中发送的查询参数的类型。它不断地抱怨下面的错误 Element implicitly has an 'any' type because the expression of type '0' can't be used to index type 'string | ParsedQs | string[] | Pa
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)
'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)
从邮递员那里,我这样传递请求
http://localhost:56368/api/v1/admin/GetUserWorkingHrs?data[]=新加坡阿洛克/ITPL/Building1/F1/Z1,预订,创建
我的后端如下
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,但是如果我在req.query.data上使用forEach循环,编译器会报告错误“找不到字符串的forEach属性”如果我把RQ.Que.DATA作为字符串,应用S拆除函数,我也会出错。
想知道,TypScript编译器如何考虑Express查询PARAM?/P>数组? 想要了解,将查询参数数组提取到本地常量标识符的正确类型应该是什么,如
const qry:any[]=req.Query.data
;对于这项任务,我得到以下错误
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)
'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)
req.query.data
的类型为string | ParsedQs | string[]| ParsedQs[]
,因此它可以是数组,也可以不是string | ParsedQs
如果它是一个ParsedQs
,当您试图访问对象的[0]
属性时,您的代码会崩溃,因为它不是数组,所以不存在。因此,您的代码流必须更改才能正常工作,如下所示:
getUserWorkingHrs=async(请求:请求,响应:响应)=>{
if(请求查询数据){
if(isArray(请求查询数据)){
doSomethingWith(请求查询数据[0]);
}
}
}
请注意,要使typescript编译器知道req.query.data是一个给定自定义isArray
函数(我假设该函数返回布尔值)的数组,必须使用type guard()对该函数进行注释,即:
函数isArray(arr:any):arr是数组{
返回!!arr.length
}
您可以将嵌套的if
条件修改为if(Array.isArray(req.query.data))
。