According to the docs a Date
object should be converted to a string
:
Note, that dates will be converted to strings when you'll try to convert class object to plain object.
My example-code with class-transformer 0.2.3
does not work as expected:
class TestDate {
@Type(() => Date)
aDate!: Date;
}
const testDate = new TestDate();
testDate.aDate = new Date();
const result: any = classToPlain(testDate);
console.log(typeof result.aDate);
This prints object
to the console, but I'd expect string
.
What am I missing?
The following sentence in the documentation is wrong (see class-transformer#326):
Note, that dates will be converted to strings when you'll try to convert class object to plain object.
The solution is to use @Transform
:
@Transform(value => (value as Date).toISOString(), {
toPlainOnly: true
})