Skip to content

Feature Request: Support of discriminated Union Types #114

@paulwer

Description

@paulwer

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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions