Typescript - 如何将查询参数解析为数值

use*_*338 9 type-conversion express typescript

我有一个快速 API 端点,我需要从查询参数接收两个数字。

问题是我无法将它们正确地转换为数字类型常量。

我总是收到以下打字稿错误: 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)
Run Code Online (Sandbox Code Playgroud)

小智 12

只是提及 Aleksey L. 所说的内容,但将其放在这里以便人们可以轻松看到答案

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)
}
Run Code Online (Sandbox Code Playgroud)

这将有助于打字稿将 req.query.page 解释为字符串,然后能够将其解析为整数。