typestack / class-validator

Decorator-based property validation for classes.
MIT License
10.87k stars 785 forks source link

feature: Pick and Omit type helpers #1031

Open scorsi opened 3 years ago

scorsi commented 3 years ago

Description

Sometime we want to take benefits of the Pick and Omit standard interface but we loose the class-validator decorators. E.g.:

class User {
  @IsUUID()
  id: string;

  @IsString()
  firstName: string;

  @IsString()
  lastName: string;
}

class CreateUser implements Pick<User, 'firstName' | 'lastName'> {
  @IsString()
  firstName: string;

  @IsString()
  lastName: string;
}

There is a lot of code duplicatation which may results in bugs.

Proposed solution

class User {
  @IsUUID()
  id: string;

  @IsString()
  firstName: string;

  @IsString()
  lastName: string;
}

class CreateUser extends PickType<User, ['firstName', 'lastName'] as const> {}
// or
class CreateUser extends OmitType<User, ['id'] as const> {}

It is much more concise and readable. Modifying the class-validator in User will change it in CreateUser too.

A good example is for the NestJS GraphQL package doc and source code.

vuggy17 commented 3 weeks ago

Any progress on this?