Search code examples
class-validatorclass-transformer

Why should we NOT use enableImplicitConversion when using class-transformer?


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


Solution

  • 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