Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 962
Srinivasan Avatar asked Oct 16 '22 03:10

Srinivasan


People also ask

What is a query string in Express?

The query string portion of a URL is the part of the URL after the question mark ? .

How can you capture query params sent by GET method?

Your query parameters can be retrieved from the query object on the request object sent to your route. It is in the form of an object in which you can directly access the query parameters you care about. In this case Express handles all of the URL parsing for you and exposes the retrieved parameters as this object.

How does Express handle multiple query parameters?

To accept multiple URL parameters in Express routes, we can put them as the placeholders for each URL parameter in the route path string. We add the '/fruit/:fruitName/:fruitColor' route, where :fruitName and :fruitColor are the URL params placeholders. We can get the values of them from the req.

How do you get variables in Express JS in the GET method?

In Express. js, you can directly use the req. query() method to access the string variables.


1 Answers

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
}
like image 106
Henke Avatar answered Oct 19 '22 02:10

Henke