6

Exclude undefined or null properties from the class. this is actual nature but I need a decorator who can ignore this

import {Expose, plainToClass} from "class-transformer";

class User {
    @Expose() id: number;
    @Expose() firstName: string;
    @Expose() lastName: string;
}

const fromPlainUser = {
  unkownProp: 'hello there',
  firstName: 'Umed',
  lastName: 'Khudoiberdiev',
}

console.log(plainToClass(User, fromPlainUser, { excludeExtraneousValues: true }))

// User {
//   id: undefined,
//   firstName: 'Umed',
//   lastName: 'Khudoiberdiev'
// }
4

1 回答 1

1

如果您创建一个类实例,那么您将拥有它的属性。如果您想要一个没有未定义属性的对象 - 只需将类实例转换回具有避免未定义字段的规则的普通对象。它不再是类实例,而是一个没有未定义字段的对象。

于 2020-04-15T08:57:13.923 回答