Search code examples
nestjsclass-validatorclass-transformer

Array of different types object - class-transformer


I'm trying to validate an array of objects that could have different types of objects. For example:

const objA = { ... } // Some properties
const objB = { ... } // Different properties from objA

The array can contain either:

const mixedArray = Array<objA | objB>;

I'm trying to validate this array coming in a property in an API

class ExampleDTO {
   @IsArray()
   @ArrayNotEmpty()
   @ValidateNested({ each: true })
   @Type(() => ????)
   readonly mixedArray: Array<objA | objB>;
}

How do I define the @Type to include multiple custom types to be validated?

Any ideas? On how to do it differently?


Solution

  • Assuming ObjA and ObjB are two classes, You have to use conditional @Transform instead of @Type, however you need at least a factor to differentiate between ObjA and ObjB.

    For example objA have a property named iAmObjA but objB does not, so you can change type decorator like this:

    class ExampleDTO {
       @IsArray()
       @ArrayNotEmpty()
       @ValidateNested({ each: true })
       @Transform(({ value }) => value?.map(o => plainToClass(o.iAmObjA ? ObjA : ObjB, o)))
       readonly mixedArray: Array<objA | objB>;
    }