#Remove the default value defined in the CreateDto when using the UpdateDto

1 messages · Page 1 of 1 (latest)

sour bough
#

In my create DTO, I defined an optional parameter with a default value. However, when using the update DTO, even though I didn't pass that parameter, it still appeared in the controller. How can I prevent this from happening?

import { IsOptional } from 'class-validator';

export class CreateAdminDto {
  readonly username: string;

  @IsOptional()
  readonly firstName?: string | null = 'admin';
}
import { PartialType } from '@nestjs/mapped-types';
import { CreateAdminDto } from './create-admin.dto';

export class UpdateAdminDto extends PartialType(CreateAdminDto) {}
jovial flare
last island
#

PartialType is just a type definition, it does not strip the value at runtime. At runtime, CreateAdminDto is instantiated when UpdateAdminDto is instantiated, therefore firstName has a default value of admin. Use a different DTO. Also, most likely unless it's a very basic CRUD application, the DTO used to Create and the DTO used to Update are not going to match.

jovial flare
rich prawnBOT
#

This post has been marked as resolved. :white_check_mark:
Please read through the conversation and resolution, if you are having the same issue. If you were the original author of the post and the issue is still fresh (within a few days) and you are still have having trouble, continue to reply here. If you are not the original author of the post or the post has aged, start a new thread linking this one as relevant to your problem, providing as much additional information as possible.

lilac bough
# sour bough In my create DTO, I defined an optional parameter with a default value. However,...

You can use OmitType to remove properties you don't want in dto.

export class UpdateAdminDto extends PartialType(OmitType(CreateAdminDto, ['firstName'] as const)) {}

See: https://docs.nestjs.com/openapi/mapped-types.
But you can't just remove default value from another dto. You can create new class like they said or redefine the same property without default value.