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
Some reasons why we should not use implicit conversion.
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 workExample:
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