简体   繁体   English

Typescript - 删除 class 的未声明属性

[英]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.我正在尝试创建一个 DTO class。但是我在寻找排除未声明属性的正确方法时遇到了问题。 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.因此,如果有人试图创建 DTO class 并添加未在 class 中声明的额外属性,则应忽略且不添加这些属性。

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.对于只有 4 个字段,我宁愿手动输入 4 行来分别分配它们,但我想如果你有更多的 DTO 和更多的字段,它可以帮助使用更通用的方法。

Here I've used Object.entries and Object.fromEntries along with a filter to exclude properties we don't need:在这里,我使用Object.entriesObject.fromEntries以及一个过滤器来排除我们不需要的属性:

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

And keys would be something like: keys会是这样的:

["email", ...]

You can also make this a function for reusability or even a decorator too.您也可以将其设为 function 以实现可重用性,甚至是装饰器。

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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