【问题标题】:Typescript - How to parse query parameters into number valueTypescript - 如何将查询参数解析为数值
【发布时间】:2021-12-10 12:19:54
【问题描述】:

我有一个快速 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)

【问题讨论】:

  • 只是帮助打字稿理解它是一个字符串:parseInt(req.query.page as string)。即使不是 - 你会得到一个NaN(与不可解析字符串相同)
  • @AlekseyL。非常感谢!

标签: typescript express type-conversion


【解决方案1】:

只是提到 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)
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    相关资源
    最近更新 更多