Search code examples
typescriptclass-validator

class-validator validate discriminated union type


I have a mongoose discriminator schema, which mean the data will be different according to one of the attributes.

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

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

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

What is the correct way to validate the Feature class so that it only accepts 2 different kinds?


Solution

  • it can be achieved by using validateNested() together with class-transformer discriminator

    class BaseFeature {
      kind: 'size' | 'color'
    }
    
    class ColorFeature extends BaseFeature {
      kind: 'color'
      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;
    }