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

Fastify无法识别自定义PasswordRequest类型的问题求助

解决Fastify + TypeScript路由请求体类型不兼容问题

问题原因

Fastify的路由处理函数类型由路由配置中的schema自动推导,你手动定义了PasswordRequest但未在路由配置中声明对应的请求体Schema,导致Fastify默认将request.body视为unknown,与你定义的类型不匹配,从而抛出类型错误。

解决方案

需要将请求体结构定义到路由的schema配置中,让Fastify同时完成运行时验证和TypeScript类型推导。

步骤1:定义请求体Schema

const changePasswordSchema = {
  body: {
    type: 'object',
    required: ['oldPassword', 'newPassword'],
    properties: {
      oldPassword: { type: 'string' },
      newPassword: { type: 'string' }
    }
  }
} as const;

添加as const可以让TypeScript精确推导Schema的类型,避免类型信息丢失。

步骤2:修改路由配置

将Schema添加到路由选项中,此时request参数会自动获得正确的类型,无需手动指定PasswordRequest:

instance.post("/password", { 
  onRequest: [authentificationMiddleware()],
  schema: changePasswordSchema
}, async(request, reply) => {
  const infos = SecurityHelpers.getUserInfos(request);
  const { oldPassword, newPassword } = request.body; // 此处body类型已自动推导为{ oldPassword: string; newPassword: string }
  const updater = await UserServices.changePassword(infos, oldPassword, newPassword);
  reply.status(httpStatus.OK).send(updater);
});

(可选)保留自定义Request类型

如果仍想使用PasswordRequest类型,可以将其与Schema关联:

// 基于Schema推导Body类型
type PasswordRequestBody = typeof changePasswordSchema.body.properties;
type PasswordRequest = FastifyRequest<{ Body: PasswordRequestBody }>;

// 路由中使用自定义类型
instance.post("/password", { 
  onRequest: [authentificationMiddleware()],
  schema: changePasswordSchema
}, async(request: PasswordRequest, reply) => {
  // 代码逻辑不变
});

关键说明

Fastify的TypeScript类型系统与JSON Schema强绑定:只有在路由配置中声明Schema,Fastify才能正确生成对应的FastifyRequest类型,既保证了运行时的请求合法性验证,又解决了类型不兼容问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:45:13