@@ -245,6 +245,62 @@ import {deserializeArray} from "class-transformer";
245
245
let photos = deserializeArray (Photo , photos );
246
246
```
247
247
248
+ ## Enforcing type-safe instance
249
+
250
+ The default behaviour of the ` plainToClass ` method is to set * all* properties from the plain object,
251
+ even those which are not specified in the class.
252
+
253
+ ``` typescript
254
+ import {plainToClass } from " class-transformer" ;
255
+
256
+ class User {
257
+ id: number
258
+ firstName: string
259
+ lastName: string
260
+ }
261
+
262
+ const fromPlainUser = {
263
+ unkownProp: ' hello there' ,
264
+ firstName: ' Umed' ,
265
+ lastName: ' Khudoiberdiev' ,
266
+ }
267
+
268
+ console .log (plainToClass (User , fromPlainUser ))
269
+
270
+ // User {
271
+ // unkownProp: 'hello there',
272
+ // firstName: 'Umed',
273
+ // lastName: 'Khudoiberdiev',
274
+ // }
275
+ ```
276
+
277
+ If this behaviour does not suit your needs, you can use the ` excludeExtraneousValues ` option
278
+ in the ` plainToClass ` method while * exposing all your class properties* as a requirement.
279
+
280
+ ``` typescript
281
+ import {Expose , plainToClass } from " class-transformer" ;
282
+
283
+ class User {
284
+ @Expose () id: number ;
285
+ @Expose () firstName: string ;
286
+ @Expose () lastName: string ;
287
+ }
288
+
289
+ const fromPlainUser = {
290
+ unkownProp: ' hello there' ,
291
+ firstName: ' Umed' ,
292
+ lastName: ' Khudoiberdiev' ,
293
+ }
294
+
295
+ console .log (plainToClass (User , fromPlainUser , { excludeExtraneousValues: true }))
296
+
297
+ // User {
298
+ // id: undefined,
299
+ // firstName: 'Umed',
300
+ // lastName: 'Khudoiberdiev'
301
+ // }
302
+ ```
303
+
248
304
## Working with nested objects
249
305
250
306
When you are trying to transform objects that have nested objects,
@@ -805,4 +861,4 @@ usages.
805
861
806
862
## Release notes
807
863
808
- See information about breaking changes and release notes [ here] ( https://github.com/pleerock/class-transformer/tree/master/doc/release-notes.md ) .
864
+ See information about breaking changes and release notes [ here] ( https://github.com/pleerock/class-transformer/tree/master/doc/release-notes.md ) .
0 commit comments