Skip to content

Commit 5c42d95

Browse files
nimaenMTschannett
authored andcommitted
add option to remove extraneous values
1 parent 23c851f commit 5c42d95

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

src/ClassTransformOptions.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ export interface ClassTransformOptions {
2626
*/
2727
strategy?: "excludeAll"|"exposeAll";
2828

29+
/**
30+
* Indicates if extraneous properties should be excluded from the value when converting a plain value to a class.
31+
*/
32+
excludeExtraneousValues?: boolean;
33+
2934
/**
3035
* Only properties with given groups gonna be transformed.
3136
*/

src/TransformOperationExecutor.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -331,7 +331,11 @@ export class TransformOperationExecutor {
331331
return key;
332332
});
333333
}
334-
keys = keys.concat(exposedProperties);
334+
if (this.options.excludeExtraneousValues) {
335+
keys = exposedProperties;
336+
} else {
337+
keys = keys.concat(exposedProperties);
338+
}
335339

336340
// exclude excluded properties
337341
const excludedProperties = defaultMetadataStorage.getExcludedProperties(target, this.transformationType);

test/functional/basic-functionality.spec.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,31 @@ describe("basic functionality", () => {
9494
});
9595
});
9696

97+
it("should exclude extraneous values if the excludeExtraneousValues option is set to true", () => {
98+
defaultMetadataStorage.clear();
99+
100+
class User {
101+
@Expose() id: number;
102+
@Expose() firstName: string;
103+
@Expose() lastName: string;
104+
}
105+
106+
const fromPlainUser = {
107+
firstName: "Umed",
108+
lastName: "Khudoiberdiev",
109+
age: 12
110+
};
111+
112+
const transformedUser = plainToClass(User, fromPlainUser);
113+
transformedUser.should.be.instanceOf(User);
114+
transformedUser.should.have.property("age");
115+
transformedUser.should.have.property("id").that.is.undefined;
116+
117+
const transformedUserWithoutExtra = plainToClass(User, fromPlainUser, { excludeExtraneousValues: true });
118+
transformedUserWithoutExtra.should.be.instanceOf(User);
119+
transformedUserWithoutExtra.should.not.have.property("age");
120+
});
121+
97122
it("should exclude all objects marked with @Exclude() decorator", () => {
98123
defaultMetadataStorage.clear();
99124

0 commit comments

Comments
 (0)