Bird
Raised Fist0
NestJSframework~10 mins

class-transformer usage in NestJS - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to transform a plain object into a class instance using class-transformer.

NestJS
import { plainToInstance } from 'class-transformer';

class User {
  name: string;
  age: number;
}

const plainUser = { name: 'Alice', age: 25 };
const user = plainToInstance(User, [1]);
console.log(user instanceof User);
Drag options to blanks, or click blank then click option'
AplainUser
Bnew User()
C{ name: 'Bob', age: 30 }
DUser
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the class name instead of the object.
Passing a new instance instead of the plain object.
2fill in blank
medium

Complete the code to exclude the password field when transforming a User object to plain using class-transformer.

NestJS
import { Exclude, plainToInstance, instanceToPlain } from 'class-transformer';

class User {
  name: string;
  @Exclude()
  [1]: string;
}

const user = plainToInstance(User, { name: 'Bob', password: 'secret' });
const plainUser = instanceToPlain(user);
console.log(plainUser);
Drag options to blanks, or click blank then click option'
Asecret
Bname
Cage
Dpassword
Attempts:
3 left
💡 Hint
Common Mistakes
Excluding the wrong property like name or age.
Trying to exclude a value instead of a property name.
3fill in blank
hard

Fix the error in the code to properly transform nested objects using class-transformer.

NestJS
import { Type, plainToInstance } from 'class-transformer';

class Photo {
  url: string;
}

class User {
  name: string;
  @Type(() => [1])
  photos: Photo[];
}

const plainUser = {
  name: 'Alice',
  photos: [{ url: 'photo1.jpg' }, { url: 'photo2.jpg' }]
};

const user = plainToInstance(User, plainUser);
console.log(user.photos[0] instanceof Photo);
Drag options to blanks, or click blank then click option'
AString
BPhoto
CUser
DObject
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong class in @Type decorator.
Omitting the @Type decorator for nested objects.
4fill in blank
hard

Fill both blanks to create a class-transformer transformer that converts a string to a number during transformation.

NestJS
import { Transform, plainToInstance } from 'class-transformer';

class Product {
  @Transform(({ value }) => [1])
  price: number;
}

const plainProduct = { price: '100' };
const product = plainToInstance(Product, plainProduct);
console.log(typeof product.price === [2]);
Drag options to blanks, or click blank then click option'
ANumber(value)
B'number'
C'string'
DparseInt(value)
Attempts:
3 left
💡 Hint
Common Mistakes
Using parseInt without returning the value.
Checking typeof against 'string' instead of 'number'.
5fill in blank
hard

Fill all three blanks to create a class-transformer setup that excludes a field, transforms a nested object, and converts a string to a boolean.

NestJS
import { Exclude, Type, Transform, plainToInstance } from 'class-transformer';

class Settings {
  @Transform(({ value }) => [1])
  darkMode: boolean;
}

class User {
  name: string;
  @Exclude()
  [2]: string;
  @Type(() => [3])
  settings: Settings;
}

const plainUser = {
  name: 'Eve',
  password: '1234',
  settings: { darkMode: 'true' }
};

const user = plainToInstance(User, plainUser);
console.log(user.password === undefined);
console.log(typeof user.settings.darkMode === 'boolean');
Drag options to blanks, or click blank then click option'
Avalue === 'true'
Bpassword
CSettings
DdarkMode
Attempts:
3 left
💡 Hint
Common Mistakes
Not excluding the password field properly.
Not converting the darkMode string to boolean.
Not using the correct class in @Type decorator.

Practice

(1/5)
1. What is the main purpose of the class-transformer library in a NestJS application?
easy
A. To convert plain JavaScript objects into class instances and vice versa
B. To handle HTTP requests and responses
C. To manage database connections
D. To style the frontend components

Solution

  1. 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.
  2. Step 2: Compare with other options

    Options B, C, and A relate to other parts of NestJS or frontend, not data transformation.
  3. Final Answer:

    To convert plain JavaScript objects into class instances and vice versa -> Option A
  4. Quick Check:

    class-transformer = object-class conversion [OK]
Hint: Remember: class-transformer changes plain objects to class instances [OK]
Common Mistakes:
  • Confusing class-transformer with HTTP or database modules
  • Thinking it styles frontend components
  • Assuming it manages server routing
2. Which decorator from class-transformer is used to exclude a property from the transformed output?
easy
A. @Expose()
B. @Exclude()
C. @Transform()
D. @Type()

Solution

  1. Step 1: Identify the decorator for exclusion

    The @Exclude() decorator marks properties to be left out during transformation.
  2. Step 2: Understand other decorators

    @Expose() includes properties, @Transform() customizes transformation, and @Type() defines property types.
  3. Final Answer:

    @Exclude() -> Option B
  4. Quick Check:

    Exclude means leave out = @Exclude() [OK]
Hint: Exclude properties with @Exclude() decorator [OK]
Common Mistakes:
  • Using @Expose() to exclude instead of include
  • Confusing @Transform() with exclusion
  • Not importing decorators correctly
3. Given the following code, what will be the output of 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);
medium
A. User { id: 1, name: 'Alice', password: 'secret' }
B. { id: 1, name: 'Alice' }
C. User { id: 1, name: 'Alice' }
D. Error: password property missing

Solution

  1. Step 1: Understand @Exclude effect on transformation

    The @Exclude() decorator removes the password property from the transformed class instance.
  2. Step 2: Analyze the output of plainToInstance

    The result is an instance of User with id and name, but no password.
  3. Final Answer:

    User { id: 1, name: 'Alice' } -> Option C
  4. Quick Check:

    @Exclude removes password = User without password [OK]
Hint: Properties with @Exclude() won't appear in class instances [OK]
Common Mistakes:
  • Expecting password to be present after transformation
  • Confusing plain object with class instance output
  • Assuming error occurs due to missing password
4. Identify the error in this NestJS code using 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?
medium
A. Missing @Expose() decorators on class properties
B. Wrong import of plainToInstance function
C. Plain object keys do not match class property names
D. excludeExtraneousValues option is not supported

Solution

  1. Step 1: Understand excludeExtraneousValues option

    This option removes all properties not marked with @Expose() during transformation.
  2. Step 2: Check class property decorators

    The Product class properties lack @Expose(), so all are excluded, resulting in an empty object.
  3. Final Answer:

    Missing @Expose() decorators on class properties -> Option A
  4. Quick Check:

    excludeExtraneousValues needs @Expose() [OK]
Hint: Use @Expose() with excludeExtraneousValues to keep properties [OK]
Common Mistakes:
  • Assuming excludeExtraneousValues disables transformation
  • Thinking plain object keys cause the issue
  • Ignoring need for decorators with this option
5. You want to transform a plain object with nested properties into class instances using 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?
hard
A. undefined, because address property is missing
B. false, because nested objects are not transformed automatically
C. Error, because @Type decorator is used incorrectly
D. true, because @Type decorator converts nested object to Address instance

Solution

  1. Step 1: Recognize the role of @Type decorator

    The @Type(() => Address) decorator tells class-transformer to convert the nested plain object into an Address class instance.
  2. Step 2: Check the output of instanceof

    Since transformation happens correctly, user.address is an instance of Address, so the output is true.
  3. Final Answer:

    true, because @Type decorator converts nested object to Address instance -> Option D
  4. Quick Check:

    @Type enables nested class conversion = true [OK]
Hint: Use @Type(() => Class) for nested object transformation [OK]
Common Mistakes:
  • Forgetting @Type causes nested objects to stay plain
  • Assuming nested objects transform automatically
  • Misusing @Type decorator syntax
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard