Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature Request: Support of discriminated Union Types #114

Open
paulwer opened this issue Nov 12, 2024 · 0 comments
Open

Feature Request: Support of discriminated Union Types #114

paulwer opened this issue Nov 12, 2024 · 0 comments

Comments

@paulwer
Copy link

paulwer commented Nov 12, 2024

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant