Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

question: How can I convert some optional parameters defined in the model without excluding the attributes not defined in the model? #1445

Open
Chen-913 opened this issue Feb 1, 2023 · 3 comments
Labels
type: question Questions about the usage of the library.

Comments

@Chen-913
Copy link

Chen-913 commented Feb 1, 2023

I was trying to...

I hope that when some parameters of the Model are optional, I can automatically remove some parameters that are not passed in, instead of changing its value to undefined.

As the example in the document:

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

// Assume that these fields are optional
class User {
  @Expose() id?: number;
  @Expose() firstName?: string;
  @Expose() lastName?: string;
}

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

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

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

The problem:

In the case of no id transfer, it is converted to undefined by default, which I don't want to do. The effect I want is that if I don't transfer the id field, the converted object will not have the id field.

I know that fields with undefined can be removed by some other methods.
for example:

console.log(JSON.parse(JSON.strigify(transformObj)));
// User {
//   firstName: 'Umed',
//   lastName: 'Khudoiberdiev'
// }

I want to ask whether this tool provides such functions or options to call to achieve this effect. I can't find it in the document.

@Chen-913 Chen-913 added the type: question Questions about the usage of the library. label Feb 1, 2023
@diffy0712
Copy link

Hello @Chen-913,

you can try the exposeUnsetFields: false option like: console.log(plainToInstance(User, fromPlainUser, { excludeExtraneousValues: true, exposeUnsetFields: false}));

@reedoso
Copy link

reedoso commented Jun 7, 2024

@diffy0712 Hello there. This is not working. All fields are undefined=(

@Chen-913
Copy link
Author

Are there any plans to fix this issue?🧐

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: question Questions about the usage of the library.
Development

No branches or pull requests

3 participants