Typescript - How to parse query parameters into number value

Viewed 1975

I have a express API endpoint where I need to receive two numbers from the query parameters.

The problem is that I cannot convert them properly into number type constants.

I always get the following typescript error: Argument of type 'string | ParsedQs | string[] | ParsedQs[]' is not assignable to parameter of type 'string'.

export const getRoutes = async (req: Request, res: Response) => {
  const page:number = parseInt(req.query.page)
  const limit:number = parseInt(req.query.limit)
1 Answers

Just mentioning what Aleksey L. said but putting it here so people can see the answer easily

export const getRoutes = async (req: Request, res: Response) => {
  const page:number = parseInt(req.query.page as string)
  const limit:number = parseInt(req.query.limit as string)
}

That would help typescript interpret req.query.page as a string and then be able to parse it as an integer.

Related