class-validator icon indicating copy to clipboard operation
class-validator copied to clipboard

feature: Pick and Omit type helpers

Open scorsi opened this issue 4 years ago • 1 comments

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.

scorsi avatar Apr 22 '21 13:04 scorsi

Any progress on this?

vuggy17 avatar Aug 20 '24 06:08 vuggy17