IntersectionType 不适用于 class-transformer

IntersectionType doesn't work with class-transformer

假设我们有以下相交class

export class PagingDto {
  @IsInt()
  @Type(() => Number)
  @ApiProperty()
  limit: number;

  @IsInt()
  @Type(() => Number)
  @ApiProperty()
  offset: number;
}

export class UserDto {
  @IsString()
  @ApiProperty()
  name: string;
}

export class UserWithPagingDto extends IntersectionType(
  PagingDto,
  UserDto,
) {}

当我尝试将它与@Query() 一起使用时,nestjs 不会按预期将限制和偏移字符串值转换为数字...

// ----- in UserController
@Get()
  find(@Query() dto: UserWithPagingDto) {
    console.log(dto)
    // output: { limit: '10', offset: '1', name: 'foo' }
    // limit & offset should be numbers...
  }


// ----- in main.ts, following config is defined to enable validation with transform
app.useGlobalPipes(
    new ValidationPipe({ transform: true }),
  );

如果我简单地将用 PagingDto 编写的所有内容都放在 UserWithPagingDto 中,它就可以正常工作。

这是否意味着 nest 不支持 class-transformer with IntersectionType 或者是否有任何解决方法?

class-transformer 以最低配置与 IntersectionType 一起工作: app.useGlobalPipes(new ValidationPipe({transform: true}));
这只是一个@nestjs/swagger 库的版本问题。 在我的例子中,从 nestjs 7 升级到 8(有效地将 @nestjs/swagger 从 4.5.12-next.1 升级到 5.1.2)解决了这个问题。

<题外话,但有用的笔记>
如果启用 transformOptions: { enableImplicitConversion: true } 选项,即使没有 @Type(() => Number) 装饰器,它也会将字符串转换为数字。

(非常感谢 @Jay McDoniel