After dedicating a significant amount of time to this task, I have discovered a more efficient approach compared to the existing solution.
The @Type
decorator provides helpful options, such as working with objects. This allows for conditional return of different types based on specific criteria, enabling validation over one of the two types:
class Feature {
name: string
@ValidateNested()
@IsDefined()
@Type(({ object }) => {
if(object.option?.kind === 'color') return ColorFeature;
else if(object.option?.kind === 'size') return SizeFeature;
// Handle edge case when previous conditions are not met
})
option: ColorFeature | SizeFeature
}
To maintain cleanliness and manage multiple types effectively, consider using a switch case
or a Record structure:
@ValidateNested()
@IsDefined()
@Type(({ object }) => {
switch(object.option?.kind){
case 'color':
return ColorFeature;
case 'size':
return SizeFeature;
case 'shape':
return ShapeFeature;
default:
// Handle edge cases
}
})
option: ColorFeature | SizeFeature | ShapeFeature
Furthermore, ensure that validation decorators are also applied in the extended classes to guarantee correct validation processes.