By default, plainToInstance sets all properties from the plain object onto the instance, even if they are not defined in the class.
To prevent this and only allow properties explicitly marked with the @Expose() decorator, use the excludeExtraneousValues: true option in plainToInstance.
import { Expose, plainToInstance } from 'class-transformer';
class User {
@Expose() id: number;
@Expose() firstName: string;
@Expose() lastName: string;
}
const fromPlainUser = {
unkownProp: 'hello there',
firstName: 'Umed',
lastName: 'Khudoiberdiev',
};
// Only id, firstName, and lastName will be present
const user = plainToInstance(User, fromPlainUser, { excludeExtraneousValues: true });
import { Expose, plainToInstance } 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(plainToInstance(User, fromPlainUser, { excludeExtraneousValues: true }));
// User {
// id: undefined,
// firstName: 'Umed',
// lastName: 'Khudoiberdiev'
// }