You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fastify+TypeScript路由变量解析失败,req.params/query类型报错

Fastify + TypeScript 路由参数类型错误排查

我正在搭建基于Fastify、TypeScript和Node.js的小型服务器,编写了如下路由代码:

fastify.get('/query_tile/:z/:x/:y', async (req, reply) => {
    const t0 = performance.now()

    const { z, x, y }: { z: string, x: string, y: string } = req.params;
    const useCache = req.query.useCache !== 'false'; // use cache by default
    // ......
})

编译时出现以下TypeScript错误:

TSError: ⨯ Unable to compile TypeScript:
src/app.ts:54:11 - error TS2739: Type '{}' is missing the following properties from type '{ z: string; x: string; y: string; }': z, x, y

54     const { z, x, y }: { z: string, x: string, y: string } = req.params;
             ~~~~~~~~~~~
src/app.ts:55:32 - error TS2339: Property 'useCache' does not exist on type 'unknown'.

55     const useCache = req.query.useCache !== 'false'; // use cache by default
                                  ~~~~~~~~

问题原因及修复方案

这两个错误都是因为没有给Fastify路由的params和query指定正确的TypeScript类型导致的:

  • Fastify默认将req.params类型推断为{},手动指定的解构类型和默认类型不匹配,触发第一个错误。
  • req.query默认类型是unknown,直接访问其属性会触发第二个错误。

修复步骤:

  • 定义Params和Query的接口:
interface TileParams {
  z: string;
  x: string;
  y: string;
}

interface TileQuery {
  useCache?: string;
}
  • 在fastify.get方法中指定泛型参数,传入上述接口:
    修改后的路由代码:
fastify.get<TileParams, TileQuery>('/query_tile/:z/:x/:y', async (req, reply) => {
    const t0 = performance.now()

    const { z, x, y } = req.params; // 自动匹配TileParams类型
    const useCache = req.query.useCache !== 'false'; // req.query为TileQuery类型
    // ......
})

如果不想单独定义接口,也可以直接在泛型中内联类型:

fastify.get<{ z: string; x: string; y: string }, { useCache?: string }>(
  '/query_tile/:z/:x/:y',
  async (req, reply) => {
    const t0 = performance.now()

    const { z, x, y } = req.params;
    const useCache = req.query.useCache !== 'false';
    // ......
  }
)

这样TypeScript就能正确推断req.params和req.query的类型,解决编译错误。

内容的提问来源于stack exchange,提问作者pcace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 05:45:11