Nestjs how to make extend partialtype(createDto) make nested properties of dtos inside createDto also optional

Viewed 1533

I have UpdateUserDto:

export class UpdateUserDto extends PartialType(CreateUserDto) {

}

CreateUserDto:

export class CreateUserDto {
  @ValidateNested({ each: true })
  @IsOptional()
  Point: CreateUserPointDto;
}

CreateUserPointDto:

 export class CreateUserPointDto{
  @IsString()
  name: string
  @IsString()
  color: string
  
}

Now partial type makes all properties of CreateUserDto optional, the problem is, it doesn't create all properties of Point that is inside CreateUserDto optional.

How do I go about solving this issue?

Also another unrelated problem, any validation to Point in UpdateUser only works with { PartialType } from '@nestjs/mapped-types'

If I use import { PartialType } from '@nestjs/swagger', For the same code it says Point.property name/color should not exist.

1 Answers

I'm sure you may have moved on from this, but here's something that may resolve the issue in case you come around in the future.

You need to use @Type from class-transformers to ensure you get the types for the nested Point attribute.

Sample code

import { Type } from 'class-transformer';

export class CreateUserDto {
  @ValidateNested({ each: true })
  @IsOptional()

  @Type(() => CreateUserPointDto) // -> this line
  Point: CreateUserPointDto;
}
Related