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

为何使用class-transformer的plainToInstance无法正确映射响应到DTO?

解决class-transformer plainToInstance返回多余字段的问题

问题原因

plainToInstance默认不会自动过滤原始对象中DTO未定义的字段,需要显式配置选项并配合装饰器标记需要保留的字段。

解决方案

1. 修改DTO,添加@Expose装饰器

给DTO中需要保留的字段添加class-transformer的@Expose装饰器,明确标记哪些字段需要被映射:

import { IsDate, IsString } from "class-validator";
import { Expose } from "class-transformer";

export class CreateContainerDto{
    @Expose()
    @IsString()
    etag: string;

    @Expose()
    @IsString()
    requestId: string;

    @Expose()
    @IsDate()
    date: Date;
}

2. 调用plainToInstance时添加配置选项

在调用plainToInstance时传入{ excludeExtraneousValues: true },开启额外字段过滤:

async createContainer(@Query('name') name:string): Promise<CreateContainerDto>  {
    console.log(name);
    
    try{
        const res = await this.imageService.createContainer(name);
        const dto = plainToInstance(CreateContainerDto, res, { 
            excludeExtraneousValues: true 
        });
        console.log(res);
        console.log(dto);
        return dto;
    } catch (error) {
        throw error;
    }
}

原理说明

  • @Expose():标记DTO中需要从原始对象提取并保留的字段。
  • excludeExtraneousValues: true:开启后,plainToInstance会自动过滤所有未被@Expose()标记的字段,最终只返回DTO中定义的字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 11:37:12