Search code examples
javascripttypescriptnestjsdto

How to access a non-defined but typed property in a non instantiated class (DTO)?


I am creating a logic to verify if all http body property are mandatorily part of my DTO. Using a custom decorator and a Interceptor in Nestjs, I could access req body in exec context metadata, but in time of validation, I should be able to verify if body properties are part of my DTO props - and those last ones I can't access though.

Despite this is actually a typescript doubt, I am telling you the context because if any of yours know another way to do what I am trying to, please feel free to let me know about that way too.

Below a code sample showing the DTO which properties I am trying to access:

export class CreateUserDTO {
  @IsString()
  @IsNotEmpty()
  name: string;

  @IsEmail()
  email: string;

  @MinLength(6)
  @MaxLength(32)
  @IsAlphanumeric()
  password: string;

  @IsOptional()
  @IsDateString()
  birthAt: string | Date;
}

// trying to do something like this, but can't access any property in transpilation time, one time they're all undefined

console.log(CreateUserDTO.prototype.birthAt);
console.log(CreateUserDTO.birthAt);

Solution

  • I could solve it by setting the 'whitelist' option to true in class-validator configs. That feature strips validated (returned) object of any properties that do not use any validation decorators.

    Refs.: https://docs.nestjs.com/techniques/validation#using-the-built-in-validationpipe