class-transformer
class-transformer copied to clipboard
question: How is excludeExtraneousValues different than the excludeAll strategy?
I was trying to make sure that the plainToClass function removes all of the properties that are not specified in the class. It looks like we can do it in two ways.
- Use the
excludeAllstrategy:
import { Expose, plainToInstance } from 'class-transformer';
class UserModel {
@Expose()
id: number;
@Expose()
name: number;
@Expose()
email: string;
}
const instance = plainToInstance(
UserModel,
{
id: 1,
name: 'John',
email: '[email protected]',
unknownProperty: 'unknown',
},
{
strategy: 'excludeAll',
}
);
- Use the
excludeExtraneousValuesoption:
import { Exclude, Expose, plainToInstance } from 'class-transformer';
class UserModel {
@Expose()
id: number;
@Expose()
name: number;
@Expose()
email: string;
}
const instance = plainToInstance(
UserModel,
{
id: 1,
name: 'John',
email: '[email protected]',
unknownProperty: 'unknown',
},
{
excludeExtraneousValues: true,
}
);
Ideally, I would like a solution where we don't have to use the @Expose() decorator on every property we want to expose if we use -excludeExtraneousValues, but that does not seem to be the case.
It looks like there is no difference between using excludeExtraneousValues and excludeAll. Am I missing something?
Tagging @nimaen :pray:
Hello,
I've the exact same question. I also tried to set @Expose() at class level, but withtout success.
I encountered the same problem, It would be nice to be able to use @Expose() at the class level, instead of having to decorate each property.
Cross linking another issue discussing largely the same thing:
- #740
Edit: I found the whitelist option on class-validator package does what we want, here.