We use class-transformer to easily convert plain data into class objects and back. This helps keep data organized and safe in NestJS apps.
class-transformer usage in NestJS
import { plainToInstance, instanceToPlain } from 'class-transformer'; const classObject = plainToInstance(ClassName, plainObject); const plainObject = instanceToPlain(classObject);
plainToInstance converts plain objects to class instances.
instanceToPlain converts class instances back to plain objects.
User class instance.import { plainToInstance } from 'class-transformer'; class User { id: number; name: string; } const plainUser = { id: 1, name: 'Alice' }; const user = plainToInstance(User, plainUser);
password field when converting to JSON.import { Exclude, Expose, plainToInstance, instanceToPlain } from 'class-transformer'; class User { id: number; @Exclude() password: string; @Expose() name: string; } const plainUser = { id: 1, name: 'Alice', password: 'secret' }; const user = plainToInstance(User, plainUser); const output = JSON.stringify(instanceToPlain(user));
This example shows how to convert plain data into a class instance and then back to a plain object while excluding the password field.
import { plainToInstance, instanceToPlain, Exclude, Expose } from 'class-transformer'; class User { id: number; @Expose() name: string; @Exclude() password: string; constructor(id: number, name: string, password: string) { this.id = id; this.name = name; this.password = password; } } // Plain data from a client const plainUser = { id: 1, name: 'Alice', password: 'mypassword' }; // Convert plain object to class instance const userInstance = plainToInstance(User, plainUser); // Convert class instance back to plain object (password excluded) const safeUser = instanceToPlain(userInstance); console.log('User instance:', userInstance); console.log('Safe user object:', safeUser);
Remember to use decorators like @Exclude() and @Expose() to control which fields appear in output.
Nested objects can also be transformed automatically if you use @Type(() => ClassName) decorator.
Always validate your data separately; class-transformer only converts data shapes.
class-transformer helps convert plain data to class objects and back.
Use decorators to include or exclude fields easily.
This keeps your data clean and safe in NestJS applications.
Practice
class-transformer library in a NestJS application?Solution
Step 1: Understand the role of class-transformer
The library is designed to transform plain objects into instances of classes and back, which helps in managing data cleanly.Step 2: Compare with other options
Options B, C, and A relate to other parts of NestJS or frontend, not data transformation.Final Answer:
To convert plain JavaScript objects into class instances and vice versa -> Option AQuick Check:
class-transformer = object-class conversion [OK]
- Confusing class-transformer with HTTP or database modules
- Thinking it styles frontend components
- Assuming it manages server routing
class-transformer is used to exclude a property from the transformed output?Solution
Step 1: Identify the decorator for exclusion
The@Exclude()decorator marks properties to be left out during transformation.Step 2: Understand other decorators
@Expose()includes properties,@Transform()customizes transformation, and@Type()defines property types.Final Answer:
@Exclude() -> Option BQuick Check:
Exclude means leave out = @Exclude() [OK]
- Using @Expose() to exclude instead of include
- Confusing @Transform() with exclusion
- Not importing decorators correctly
console.log(userTransformed)?
import { plainToInstance, Exclude } from 'class-transformer';
class User {
id: number;
name: string;
@Exclude() password: string;
}
const plainUser = { id: 1, name: 'Alice', password: 'secret' };
const userTransformed = plainToInstance(User, plainUser);
console.log(userTransformed);Solution
Step 1: Understand @Exclude effect on transformation
The@Exclude()decorator removes thepasswordproperty from the transformed class instance.Step 2: Analyze the output of plainToInstance
The result is an instance ofUserwithidandname, but nopassword.Final Answer:
User { id: 1, name: 'Alice' } -> Option CQuick Check:
@Exclude removes password = User without password [OK]
- Expecting password to be present after transformation
- Confusing plain object with class instance output
- Assuming error occurs due to missing password
class-transformer:
import { plainToInstance } from 'class-transformer';
class Product {
id: number;
name: string;
}
const plainProduct = { id: 10, name: 'Book' };
const product = plainToInstance(Product, plainProduct, { excludeExtraneousValues: true });
console.log(product);
Why does product print an empty object?Solution
Step 1: Understand excludeExtraneousValues option
This option removes all properties not marked with@Expose()during transformation.Step 2: Check class property decorators
TheProductclass properties lack@Expose(), so all are excluded, resulting in an empty object.Final Answer:
Missing @Expose() decorators on class properties -> Option AQuick Check:
excludeExtraneousValues needs @Expose() [OK]
- Assuming excludeExtraneousValues disables transformation
- Thinking plain object keys cause the issue
- Ignoring need for decorators with this option
class-transformer. Which approach correctly handles nested objects?
import { plainToInstance, Type } from 'class-transformer';
class Address {
street: string;
city: string;
}
class User {
name: string;
@Type(() => Address)
address: Address;
}
const plainUser = {
name: 'Bob',
address: { street: 'Main St', city: 'Townsville' }
};
const user = plainToInstance(User, plainUser);
console.log(user.address instanceof Address);
What will console.log output and why?Solution
Step 1: Recognize the role of @Type decorator
The@Type(() => Address)decorator tells class-transformer to convert the nested plain object into anAddressclass instance.Step 2: Check the output of instanceof
Since transformation happens correctly,user.addressis an instance ofAddress, so the output istrue.Final Answer:
true, because @Type decorator converts nested object to Address instance -> Option DQuick Check:
@Type enables nested class conversion = true [OK]
- Forgetting @Type causes nested objects to stay plain
- Assuming nested objects transform automatically
- Misusing @Type decorator syntax
Ready to prove it?
Pass the test and this pattern moves unknown
