Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 632
TmTron Avatar asked May 17 '26 16:05

TmTron


1 Answers

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

like image 114
TmTron Avatar answered May 22 '26 08:05

TmTron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!