6

The class-transformer docs say:

Implicit type conversion
NOTE If you use class-validator together with class-transformer you propably DON'T want to enable this function.

Why not?

I did some tests and found no issues.
Actually it is the other way around: using class-transformer (with enableImplicitConversion=true and reflect-metadata) in combination with class-validator seems to be a perfect fit and it is supported out-of-the-box by NestJS

TmTron
  • 17,012
  • 10
  • 94
  • 142

1 Answers1

11

Some reasons why we should not use implicit conversion.

It is too lenient

e.g. when we use @IsString() every type will pass the validation - even a plain object will be converted to the string [object Object], which is probably not what you want

here's a stackblitz example

@Transform() may not work

Example:

class Test {
  @Transform(value => (value === "zero" ? 0 : value), {
    toClassOnly: true
  })
  val: number;
}
const transformed = plainToClass(Test, {
    val: 'zero'
  }, {
    enableImplicitConversion
  });

// transformed.val = NaN 

The problem here is that the implicit conversion is already happening before @Transform() and since it cannot convert the string to a number it sets the value to NaN

Transform Stackblitz example

TmTron
  • 17,012
  • 10
  • 94
  • 142
  • Also, you might have issues with booleans, as the value 'false' will be interpreted as true. see https://stackoverflow.com/questions/59046629/boolean-parameter-in-request-body-is-always-true-in-nestjs-api – yuval.bl Apr 27 '21 at 17:33