#Cherypick props from dto

14 messages · Page 1 of 1 (latest)

lone patio
#

Hello, i have a dto for each entity in my backend.

What i wanted to do:

lets say i have this dto:

export class UserDto {
  @IsString()
  firstName: string;

  @IsString()
  lastName: string;

  @IsString()
  id: string;

  @IsEmail()
  email: string;
}

And i want to create a new DTO named "UpdateUserDto" that should only have firstName and lastName

What i imagined:

export class UpdateUserDto extends Pick<UserDto, "firstName", "lastName"> { }

But this wont work sadly.

Is there maybe a way to create a type that will do what i want?

charred knot
worthy summit
charred knot
#

nop

worthy summit
#

I mean, of course we can take it as a reference, but I don't know if it works with class-validator / class-transform

lone patio
charred knot
#

I belive so

#

npm i @nestjs/mapped-types

lone patio
#

Cool thanks :D ill try it out :)

lone patio
# charred knot `npm i @nestjs/mapped-types`

So i just tried it with this:

import { IsString } from "class-validator";
import { OmitType, PartialType } from "@nestjs/mapped-types";

class UserDto {
  @IsString()
  email: string;

  @IsString()
  firstName: string;

  @IsString()
  lastName: string;
}

export class UpdateUserDto extends PartialType(OmitType(UserDto, ["email"])) {}

but its just excluding the email and showing firstName and lastName now as seen in the screenshot

charred knot
#

I didn't follow why not just extends PickType(UserDto, ['firstName', 'lastName'])
as per your first try

#

tbh I don't like using those utilities for DTO classes
Just duplicate that code
I think it's easier to follow and bug-free

lone patio
#

yep got it, needed PickType and not OmitType..

#

Thanks :) imma test it now with some requests but it looks like its working