plainToClass 不会将日期转换为字符串
plainToClass does not convert a Date to string
根据 the docs,Date
对象应转换为 string
:
Note, that dates will be converted to strings when you'll try to convert class object to plain object.
我使用 class-transformer 0.2.3
的示例代码没有按预期工作:
class TestDate {
@Type(() => Date)
aDate!: Date;
}
const testDate = new TestDate();
testDate.aDate = new Date();
const result: any = classToPlain(testDate);
console.log(typeof result.aDate);
这会将 object
打印到控制台,但我希望 string
.
我错过了什么?
文档中的以下句子是错误的(参见class-transformer#326):
Note, that dates will be converted to strings when you'll try to convert class object to plain object.
解决方法是使用@Transform
:
@Transform(value => (value as Date).toISOString(), {
toPlainOnly: true
})
为了扩展 TmTron 的答案,我需要创建两个转换器 - 每个方向一个。然后我使用 :
将它们组合成一个装饰器
// TransformDate.ts
import { Transform } from "class-transformer";
export default function TransformDate() {
const toPlain = Transform((value) => (value as Date).toISOString(), {
toPlainOnly: true,
});
const toClass = Transform((value) => new Date(value), {
toClassOnly: true,
});
return function (target: any, key: string) {
toPlain(target, key);
toClass(target, key);
};
}
用法:
// User.ts
import TransformDate from './TransformDate';
export default class User {
id: string;
@TransformDate()
createdDate: Date;
// ...
}
根据 the docs,Date
对象应转换为 string
:
Note, that dates will be converted to strings when you'll try to convert class object to plain object.
我使用 class-transformer 0.2.3
的示例代码没有按预期工作:
class TestDate {
@Type(() => Date)
aDate!: Date;
}
const testDate = new TestDate();
testDate.aDate = new Date();
const result: any = classToPlain(testDate);
console.log(typeof result.aDate);
这会将 object
打印到控制台,但我希望 string
.
我错过了什么?
文档中的以下句子是错误的(参见class-transformer#326):
Note, that dates will be converted to strings when you'll try to convert class object to plain object.
解决方法是使用@Transform
:
@Transform(value => (value as Date).toISOString(), {
toPlainOnly: true
})
为了扩展 TmTron 的答案,我需要创建两个转换器 - 每个方向一个。然后我使用
// TransformDate.ts
import { Transform } from "class-transformer";
export default function TransformDate() {
const toPlain = Transform((value) => (value as Date).toISOString(), {
toPlainOnly: true,
});
const toClass = Transform((value) => new Date(value), {
toClassOnly: true,
});
return function (target: any, key: string) {
toPlain(target, key);
toClass(target, key);
};
}
用法:
// User.ts
import TransformDate from './TransformDate';
export default class User {
id: string;
@TransformDate()
createdDate: Date;
// ...
}