Srinivasan
Srinivasan

Reputation: 77

How to type bound the Express query param as an Array of string in Typescript

I am passing an array of query strings from postman to my Nodejs server written in typescript. in my backend code Typescript compiler could not understand the type of the query param sent in the query field of the express request object. It kept complaining below error.

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)

from postman I am passing the request like this

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

My backEnd is as below.

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

for my check on isArray(req.query.param), I am getting true and the length of the array returns 1, but if I use forEach loop on req.query.data, compiler reports error "can not find the property forEach for a string" and if I consider the req.query.data as a string and apply split function I am getting error too.

want to understand, how the typescript compiler consider the array of express query param?

want to understand, what should be the correct type to extract the Array of Query param to the local constant identifier like this const qry:any[] = req.query.data; for this assignment, I am getting below error.

'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)

Upvotes: 6

Views: 12756

Answers (1)

Henke
Henke

Reputation: 394

req.query.data is of type string | ParsedQs | string[] | ParsedQs[], so it can be either an array or not of string | ParsedQs.

In the case that it's a ParsedQs, your code would crash, as you're trying to access the [0] property of the object, which doesn't exist as it isn't a array. So your code flow must change for that to work, like so:

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

be aware that for the typescript compiler to know that the req.query.data is an array given your custom isArray function(that I assume returns a boolean), you have to annotate that function with a type guard(https://www.typescriptlang.org/docs/handbook/advanced-types.html), i.e.:

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

Upvotes: 3

Related Questions