Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class-transformer Exclude undefined properties

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'
// }
like image 715
Akash Gupta Avatar asked Nov 06 '22 09:11

Akash Gupta


1 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.

like image 73
satanTime Avatar answered Dec 08 '22 19:12

satanTime