gpt4 book ai didi

typescript - 类验证器验证联合类型

转载 作者:行者123 更新时间:2023-12-04 01:34:37 32 4
gpt4 key购买 nike

我有一个 mongoose discriminator schema ,这意味着数据将根据属性之一而不同。

class Feature {
name: string
option: ColorFeature|SizeFeature
}

class ColorFeature {
kind: 'color'
color: string
}

class SizeFeature {
kind: 'size'
size: number
}

验证 Feature 的正确方法是什么?类,以便它只接受 2 种不同的类型?

最佳答案

可以通过使用 validateNested() 来实现连同class-transformer discriminator

class BaseFeature {
kind: 'size' | 'color'
}

class ColorFeature extends BaseFeature {
kind: 'size'
color: string
}

class SizeFeature extends BaseFeature {
kind: 'size'
size: number
}


class Feature {
name: string

@ValidateNested()
@Type(() => BaseFeature, {
keepDiscriminatorProperty: true,
discriminator: {
property: 'kind',
subTypes: [
{ value: SizeFeature, name: 'size' },
{ value: ColorFeature, name: 'color' },
],
},
})
option: SizeFeature | ColorFeature;
}

关于typescript - 类验证器验证联合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60058260/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com