如何在NestJS控制器中正确为HTTP请求添加类型?
在NestJS中为请求参数使用类型安全的类型
NestJS默认基于Express,你可以直接使用express包中的Request类型替代any来实现类型安全;如果项目使用Fastify适配器,则对应使用FastifyRequest类型。
步骤1:导入对应类型
针对Express(默认适配器)
确保已安装@types/express(NestJS初始化项目时通常已自动包含),然后在控制器文件中导入:
import { Request } from 'express';
针对Fastify适配器
若项目基于Fastify构建,导入FastifyRequest:
import { FastifyRequest } from '@nestjs/platform-fastify';
步骤2:替换any为类型安全的请求类型
修改你的控制器代码,将request: any替换为对应类型:
import { Controller, Post, Body, Request, UsePipes } from '@nestjs/common'; import { Request } from 'express'; // 若用Fastify则替换为FastifyRequest import { MongoSanitizePipe } from './your-pipe-path'; import { Service } from './your-service-path'; import { RequestBody } from './your-body-type-path'; @Controller('endpoint') @UsePipes(new MongoSanitizePipe()) export class RequestController { constructor(private service: Service) {} @Post('post') async onAction( @Body() body: RequestBody, @Request() request: Request, // 这里替换为对应的类型 ): Promise<void> { return this.service.onAction(body, request.headers); } }
自定义请求扩展(可选)
如果你的请求对象包含自定义属性(比如通过守卫添加的user字段),可以扩展基础请求类型:
import { Request } from 'express'; // 定义自定义请求类型 interface CustomRequest extends Request { user: { id: string; username: string }; // 示例自定义字段 } // 在控制器中使用扩展后的类型 @Post('post') async onAction( @Body() body: RequestBody, @Request() request: CustomRequest, ): Promise<void> { console.log(request.user.id); // 此时会有完整的类型提示 return this.service.onAction(body, request.headers); }
内容的提问来源于stack exchange,提问作者André
相关产品推荐
相关产品推荐

