class-transformer: plainToClass assign unknown properties

Hi, I don’t know if this is a known issue since I could not find any. Fact is, the plainToClass method assigns unknown properties to the class.

class User {
  id: number
  firstName: string
  lastName: string
  password: string
}

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

console.log(plainToClass(User, fromPlainUser))

Result is :

User {
  unkownProp: 'hello there',
  firstName: 'Umed',
  lastName: 'Khudoiberdiev',
  password: 'imnosuperman' 
}

The only workaround that I saw looking at the doc would be to add an @Exclude decorator on the class and an @Expose decorator on each property, which is not really convenient… Any other workaround ? Is this a known thing ?

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 8
  • Comments: 34 (14 by maintainers)

Most upvoted comments

Please release a new version. This option would be so fucking important…

Still waiting for new version with ‘excludeExtraneousValues’ option included.

excludeExtraneousValues is not yet included in an npm version 😕

For people who are using this in combination with class-validator and thus are decorating the objects with @IsString() for example anyway.

I wrote a little extension that uses those decorators to strip all unknown properties from the object. https://gist.github.com/ljobse/a617ca62e7d0277a8da351479656f04f

The file just needs to be loaded and the plainToClass function will now strip all properties which are not decorated with anything.

@MTschannett @NoNameProvided Hey, can we get the latest changes in NPM please, thanks!

Well, there won’t be any magic. It would be only usable like this:

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

const plainUser = {
  firstName: "Umed",
  lastName: "Khudoiberdiev",
  age: 12
};

plainToClass(User, plainUser, { excludeExtraneousValues: true })

And this would log :

User (
  id: undefined,
  firstName: "Umed",
  lastName: "Khudoiberdiev"
)

Yeah i know . I’ll try to talk to @NoNameProvided to talk about the right permissions

Could a collaborator publish a new version please ? @NoNameProvided maybe ?

Nah, I’m a mere OSS contributor, I’m not a Typestack member.

You could use {whitelist: true} on the class-validator instead of excludeExtraneousValues in class-transformer

I faced same problem! 😭 Please release a new version.

Well, I’m waiting for a response from the core team now 😃

Sorry, I somehow forgot about it 👼 I’ll try to have a look in the week.

@nimaen Please do 😃