简体   繁体   中英

Typescript - Remove undeclared properties of a class

I am trying to create a DTO class. But I am having issues finding a proper way to exclude undeclared properties. So if some one tries to create a DTO class and adds extra properties that are not declared inside the class then those properties should be ignored and not be added.

import { IsString, MinLength } from 'class-validator'

export class CreateUserDto {
  @IsString()
    email: string

  @IsString()
  @MinLength(6)
    password: string

  @IsString()
    firstname: string

  @IsString()
    lastname: string

  constructor (payload: any) {
    const dto = Object.assign(this, payload)

    console.log(dto)
  }
}

For only 4 fields, I'd rather manually type out 4 lines to assign them each, but I guess if you have more DTO's with a lot more fields it could help with a more versatile method.

Here I've used Object.entries and Object.fromEntries along with a filter to exclude properties we don't need:

const dto = Object.assign(this, Object.fromEntries(Object.entries(payload).filter(([k]) => keys.includes(k))))

And keys would be something like:

["email", ...]

You can also make this a function for reusability or even a decorator too.

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM