首页 > 解决方案 > 如何使用 Typescript 输入 Express 查询参数?

问题描述

我将所有中间件功能键入为

express.RequestHandler<
  { /* route params */ },
  { /* response body */ },
  { /* request body */ },
  { /* query params */ }
>

然后我将它们作为数组传递给相应的路由处理程序,例如

const getHandler: [RequestHandler<...>, RequestHandler<...>] = [(req, res, next) => {...}, (req, res, next) => {...}]
app.get("/", getHandler)

这适用于我的大多数路线,除了我的 RequestHandler 看起来像这样的一个特定路线:

RequestHandler<{}, {}, {}, { [key: string]: string | undefined }>

我这样输入它是因为我不关心确切的属性名称,只是想缩小 to 的默认string | ParsedQs | string[] | ParsedQs[] | undefined类型string | undefined。出于某种原因,这会引发错误:

No overload matches this call.
  The last overload gave the following error.
    Argument of type '[RequestHandler<{}, {}, {}, { [key: string]: string | undefined }, Record<string, any>>]' is not assignable to parameter of type 'Application'.ts(2769)

奇怪的是,当我像这样在路由控制器中传播数组时:app.get("/", ...getHandler)它可以工作并且不再抛出错误。知道为什么会这样吗?

标签: typescriptexpress

解决方案


推荐阅读