class-transformer Exclude undefined properties

Viewed 10619

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'
// }
2 Answers

If you create a class instance then you'll have its properties. If you want to have an object without undefined properties - simply convert a class instance back to a plain object with rules that avoid undefined fields. It won't be a class instance anymore, but it will be an object without undefined fields.

add exposeUnsetFields to your options plain object. Should be:


plainToClass(User, fromPlainUser, { excludeExtraneousValues: true, exposeUnsetFields: false, })
Related