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

Fastify+TypeScript中使用fastify-multer无法访问request.file求助

Fastify + TypeScript 中 fastify-multer 无法识别 request.file 类型问题

问题场景

首次使用Fastify搭配TypeScript开发,采用Sequelize作为ORM,使用fastify-multer上传图片时流程正常,但TypeScript提示request.file属性不存在,实际运行时文件上传功能可以工作,但类型校验不通过。

相关配置与代码

package.json 配置

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.ts",
  "scripts": {
    "build": "tsc -p tsconfig.json",
    "start": "nodemon index.ts"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "fastify": "^4.13.0",
    "fastify-multer": "^2.0.3",
    "mysql2": "^3.1.2",
    "sequelize": "^6.29.0"
  },
  "devDependencies": {
    "@types/node": "^18.14.2",
    "typescript": "^4.9.5"
  }
}

路由代码

import { FastifyInstance, RouteGenericInterface } from "fastify";
import SliderController from "./controller";
import SSlider from "./type";
import { Model } from "sequelize";
import { upload } from "../../upload";
module.exports = function Slider(
  app: FastifyInstance,
  prefix: string,
  done: any
) {
 
  app.post(
    "/create",
    { preHandler: upload.single("myfile") },
    async (request, reply) => {
      console.log(request.file); // Property 'file' does not exist on type 'FastifyRequest<RouteGenericInterface, RawServerDefault, IncomingMessage, FastifySchema, FastifyTypeProviderDefault, unknown, FastifyBaseLogger, ResolveFastifyRequestType<...>>'
      reply.send("ok");
    }
  );

  done();
};

解决方法

问题根源是TypeScript默认没有识别fastify-multer为FastifyRequest扩展的file/files属性,需要补充类型定义:

  1. 安装multer类型依赖
    fastify-multer基于multer封装,需安装multer的类型声明:
npm install @types/multer --save-dev
  1. 扩展FastifyRequest类型
    在项目中创建类型声明文件(如types/fastify-multer.d.ts),添加以下内容:
import { FastifyRequest } from 'fastify';
import { File } from 'multer';

declare module 'fastify' {
  interface FastifyRequest {
    file?: File;
    files?: File[] | { [fieldname: string]: File[] };
  }
}
  1. 配置TypeScript识别类型文件
    修改tsconfig.json,确保类型声明文件被编译器识别:
{
  "compilerOptions": {
    // 保留原有配置,新增typeRoots
    "typeRoots": ["./node_modules/@types", "./types"]
  },
  "include": [
    "src/**/*",
    "types/**/*" // 包含自定义类型文件目录
  ]
}
  1. 路由中优化类型(可选)
    如果需要更精确的类型约束,可以扩展RouteGenericInterface或直接使用类型断言:
// 方式1:类型断言(快速解决)
console.log((request as any).file);

// 方式2:扩展泛型类型(推荐)
import { File } from 'multer';

interface UploadRoute extends RouteGenericInterface {
  // 可添加Body、Query等其他类型定义
}

app.post<UploadRoute>(
  "/create",
  { preHandler: upload.single("myfile") },
  async (request, reply) => {
    console.log(request.file); // 类型校验通过
    reply.send("ok");
  }
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 23:32:13