-
Notifications
You must be signed in to change notification settings - Fork 37
Open
Description
When using discriminated unions by a class-validator (at)Type() function the infer fails, because it will not pass a valid variable to the type function.
class StringType {
@IsIn(['stringType'])
type!: 'stringType';
@IsString()
stringVal!: string;
}
class NumberType {
@IsIn(['numberType'])
type!: 'numberType';
@IsNumber()
numVal!: number;
}
class BooleanType {
@IsIn(['booleanType'])
type!: 'booleanType';
@IsBoolean()
boolVal!: boolean;
}
class DiscriminatedUnionType {
@IsIn(['stringType', 'numberType', 'booleanType'])
type!: 'stringType' | 'numberType' | 'booleanType';
@ValidateNested()
@Type((obj) => {
switch (obj?.object.type) {
case 'stringType':
return StringType;
case 'numberType':
return NumberType;
case 'booleanType':
return BooleanType;
default:
throw new Error(`Invalid type: ${obj?.object.type}`);
}
})
element!: StringType | NumberType | BooleanType;
}
export class NestedUnionSchema {
@ArrayNotEmpty()
@ValidateNested({ each: true })
@Type(() => DiscriminatedUnionType)
elements!: DiscriminatedUnionType[];
}
Any suggestions how to change the classes or could this be a supported feature in the future?
Metadata
Metadata
Assignees
Labels
No labels