9

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)
2
  • 5
    Just help typescript to understand it is a string: parseInt(req.query.page as string). Even if it is not - you'll get a NaN (same as with non parsable string)
    – Aleksey L.
    Commented Dec 10, 2021 at 12:31
  • 1
    Also related stackoverflow.com/questions/63579867/…
    – Aleksey L.
    Commented Dec 10, 2021 at 12:34

1 Answer 1

14

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.