跟着我走,可能会变得有些混乱:
现在的问题是,我的鉴别器是一个包含7个值的枚举,其中6个指向一个类,最后一个指向另一个类。问题是,无论枚举类型是什么,当进行序列化时,它总是被更改为第一个子类型。
enum DiscrType = {A: "a", B: "b", C: "c"}
class Discriminator {
@IsEnum(DiscrType)
type: DiscrType
}
class ClassONE extends Discriminator {...}
class ClassTWO extends Discriminator {...}
class Stuff {
@Type(() => Discriminator, {
discriminator: {
property: 'type',
subTypes: [
{ value: ClassTWO, name: DiscrType.C},
{ value: ClassONE, name: DiscrType.A}, // Always turns into this value even if it was B
{ value: ClassONE, name: DiscrType.B},
],
},
keepDiscriminatorProperty: true,
})
@Transform(
({ value }) =>
value?.map((object: ClassONE | ClassTWO ) =>
object.type === DiscrType.C
? plainToClass(classTWO, object)
: plainToClass(ClassONE, object),
),
)
@ValidateNested({each: true})
property: (ClassONE | ClassTWO )[]
}
行为:
new Stuff({type: DiscrType.B,...}) // Serialization with Class Serializer
// Expected:
x = {type: "b",...}
// Actual:
x = {type: "a",...}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
到目前为止,我不确定这是否是完美的解决方案,但在我的项目中,将@Type替换为这个后,所有的测试仍然可以运行。
@Type((value) => value.object.type === DiscrType.C? ClassTWO: ClassONE, )既然这个方法有效,我将把它作为解决方案,但请提到如果你知道为什么应该使用鉴别器而不是这个解决方案,有什么好处?