Express Request .query.xyz as string | string[]

Viewed 2735

I am trying to assign a type to my variable, that gets its value from express' Request query. The req.query is of type "QueryString.ParsedQs" and for example req.query.accountId is of type "string | QueryString.ParsedQs | string[] | QueryString.ParsedQs[]"

How could i extract the value from req.query.accountId to always be of type string?

Example code:

import { Request, Response } from "@feathersjs/express";
class Xyz {
    public myMethod( req: Request, res: Response ){
        const accountId =req.query.accountId;/* type is "string | QueryString.ParsedQs | string[] | QueryString.ParsedQs[]"*/
    }
}
1 Answers

You can either check whether a ‛string‛ was passes:

if (typeof accounId === 'string')  {
  // do stuff
}

Or convert it (forcefully, i would not recommend) it to a string:

accountId = String(req.query.accountId);
// Or shorter
accountId = '' + req.query.accountId;

If though it was not a string before conversion you will end up with something like ‛[Object array]‛

Related