Skip to content

Commit 9b15f64

Browse files
nimaenMTschannett
authored andcommitted
Add documentation
1 parent 5c42d95 commit 9b15f64

File tree

1 file changed

+57
-1
lines changed

1 file changed

+57
-1
lines changed

README.md

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,62 @@ import {deserializeArray} from "class-transformer";
245245
let photos = deserializeArray(Photo, photos);
246246
```
247247

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+
248304
## Working with nested objects
249305

250306
When you are trying to transform objects that have nested objects,
@@ -805,4 +861,4 @@ usages.
805861

806862
## Release notes
807863

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

Comments
 (0)