NestJS中如何将DTO接收的string类bigint参数转为原生bigint类型
问题原因
HTTP请求传递的参数(Query、Body等)在原生解析后仅存在字符串、数字两种基础类型,TypeScript的类型声明仅作用于编译阶段,运行时无类型转换逻辑,因此直接声明amount: bigint不会自动触发类型转换,拿到的始终是原始的字符串值。
解决步骤
1. 安装依赖
需要用到class-transformer和class-validator两个库实现DTO的自动转换与校验,NestJS的ValidationPipe默认基于这两个库实现:
npm install class-transformer class-validator
2. 配置全局ValidationPipe
在项目入口main.ts中开启全局校验管道的自动转换功能:
import { ValidationPipe } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); // 开启参数自动转换 app.useGlobalPipes(new ValidationPipe({ transform: true })); await app.listen(3000); } bootstrap();
3. 改造DTO添加转换逻辑
使用class-transformer的@Transform装饰器为bigint字段添加转换规则,可同时添加校验逻辑避免非法值报错:
import { Transform } from 'class-transformer'; import { IsNotEmpty, Matches } from 'class-validator'; export class Foo { @Transform(({ value }) => { // 非数字格式直接抛出异常,避免转bigint失败 if (!/^\d+$/.test(value)) { throw new Error('amount必须为数字格式'); } return BigInt(value); }) @IsNotEmpty() amount: bigint; }
4. 验证效果
改造完成后控制器中拿到的query.amount就会是bigint类型,注意你原示例代码中错误引用了类的静态属性,需要取DTO实例的值:
@Get("") async foo(@Query() query: Foo) { console.log(typeof query.amount) // 输出bigint }
注意事项
- 如果bigint值超过JS安全整数范围,要求前端必须传递字符串格式的数字,避免精度丢失
- 若返回bigint给前端时出现序列化错误,可以全局配置JSON序列化规则将bigint转成字符串,避免响应报错
内容的提问来源于stack exchange,提问作者Artem
相关产品推荐
相关产品推荐

