Bird
Raised Fist0
NestJSframework~10 mins

DTO class creation in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - DTO class creation
Define DTO class
↓
Add properties with types
↓
Use decorators for validation
↓
Export DTO class
↓
Use DTO in controller/service
This flow shows how to create a DTO class by defining it, adding typed properties, applying validation decorators, exporting it, and then using it in your NestJS app.
Execution Sample
NestJS
import { IsString, IsInt } from 'class-validator';

export class CreateUserDto {
  @IsString()
  name: string;

  @IsInt()
  age: number;
}
Defines a DTO class with two properties, name and age, each with validation decorators.
Execution Table
StepActionCode LineEffect
1Import validation decoratorsimport { IsString, IsInt } from 'class-validator';Decorators available for use
2Define DTO classexport class CreateUserDto {Class CreateUserDto created
3Add name property with @IsString@IsString() name: string;Property 'name' expects a string and is validated
4Add age property with @IsInt@IsInt() age: number;Property 'age' expects an integer and is validated
5Close the DTO class}DTO class ready for import and use
6Use DTO in controller/servicee.g. create(@Body() createUserDto: CreateUserDto)DTO validates incoming data automatically
💡 DTO class fully defined and ready to validate data in NestJS
Variable Tracker
VariableStartAfter Step 3After Step 4Final
CreateUserDtoundefinedClass with 'name' property typed stringClass with 'name' and 'age' properties typedComplete DTO class with validation decorators
Key Moments - 2 Insights
Why do we use decorators like @IsString() on properties?
Decorators tell NestJS how to validate each property. See execution_table step 3 and 4 where @IsString and @IsInt are applied to properties.
Can we use DTO without exporting the class?
No, the 'export' keyword (step 2) makes it available to other files like controllers. Without export, NestJS can't use it.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what happens at step 3?
AAdd a property 'name' with string type and validation
BImport validation decorators
CExport the DTO class
DUse DTO in controller
💡 Hint
Check the 'Action' and 'Effect' columns at step 3 in execution_table
At which step is the DTO class made available for use in other files?
AStep 5
BStep 4
CStep 2
DStep 6
💡 Hint
Check the code line for step 2 in execution_table
If we remove @IsInt() decorator from 'age', what changes in the execution?
A'age' becomes a string
BNo validation on 'age' property
CDTO class won't compile
D'name' property loses validation
💡 Hint
Refer to step 4 where @IsInt() applies validation to 'age'
Concept Snapshot
DTO class creation in NestJS:
- Define a class with export
- Add typed properties
- Use class-validator decorators (@IsString, @IsInt)
- Import and use DTO in controllers/services
- Validates incoming data automatically
Full Transcript
To create a DTO class in NestJS, first import validation decorators from 'class-validator'. Then define and export a class with typed properties. Apply decorators like @IsString or @IsInt to each property to specify validation rules. This class can then be imported and used in controllers or services to validate incoming data automatically. The execution steps show importing decorators, defining the class, adding properties with decorators, exporting the class, and using it in the app.

Practice

(1/5)
1. What is the main purpose of a DTO class in a NestJS application?
easy
A. To handle database connections and queries
B. To create UI components for the frontend
C. To define the shape and validation rules of data transferred between layers
D. To manage application routing and middleware

Solution

  1. Step 1: Understand the role of DTOs

    DTO stands for Data Transfer Object, used to define how data should look when sent or received.
  2. Step 2: Identify what DTOs do in NestJS

    In NestJS, DTOs specify the structure and validation of data between client and server or between app layers.
  3. Final Answer:

    To define the shape and validation rules of data transferred between layers -> Option C
  4. Quick Check:

    DTO = Data shape and validation [OK]
Hint: DTOs organize and validate data structure in NestJS [OK]
Common Mistakes:
  • Confusing DTOs with database models
  • Thinking DTOs handle routing or UI
  • Assuming DTOs manage middleware
2. Which of the following is the correct way to declare a required string property name in a NestJS DTO class using class-validator decorators?
easy
A. @IsString() name: string;
B. name: string;
C. @IsOptional() name: string;
D. @IsNumber() name: string;

Solution

  1. Step 1: Identify the decorator for string validation

    The @IsString() decorator from class-validator ensures the property is a string and required by default.
  2. Step 2: Check other options

    name: string; lacks validation, C marks it optional, and D wrongly uses number validation.
  3. Final Answer:

    @IsString() name: string; -> Option A
  4. Quick Check:

    Use @IsString() for required string fields [OK]
Hint: Use @IsString() to require string fields in DTOs [OK]
Common Mistakes:
  • Omitting validation decorators
  • Using @IsOptional() for required fields
  • Applying wrong type decorators like @IsNumber()
3. Given this DTO class, what will be the result of validating an object { name: "Alice", age: 25 }?
import { IsString, IsInt, IsOptional } from 'class-validator';

export class UserDto {
  @IsString()
  name: string;

  @IsInt()
  @IsOptional()
  age?: number;
}
medium
A. Validation passes because name is string and age is optional integer
B. Validation fails because age is required but missing
C. Validation fails because name is not optional
D. Validation passes only if age is a string

Solution

  1. Step 1: Analyze the DTO decorators

    Name is required string, age is optional integer due to @IsOptional() and @IsInt().
  2. Step 2: Check the input object

    Input has name as string "Alice" and age as number 25, matching the DTO rules.
  3. Final Answer:

    Validation passes because name is string and age is optional integer -> Option A
  4. Quick Check:

    Required string + optional int with valid data = pass [OK]
Hint: Optional fields pass validation if present and valid [OK]
Common Mistakes:
  • Assuming optional fields must be present
  • Confusing @IsOptional() effect
  • Thinking validation fails if optional field is present
4. Identify the error in this DTO class that causes validation to always fail for the email property:
import { IsEmail } from 'class-validator';

export class EmailDto {
  @IsEmail
  email: string;
}
medium
A. Should import IsString instead of IsEmail
B. email property should be optional
C. email property type should be number
D. Missing parentheses after @IsEmail decorator

Solution

  1. Step 1: Check decorator usage

    @IsEmail is a function decorator and must be called with parentheses: @IsEmail()
  2. Step 2: Understand effect of missing parentheses

    Without parentheses, the decorator is not applied properly, causing validation to fail.
  3. Final Answer:

    Missing parentheses after @IsEmail decorator -> Option D
  4. Quick Check:

    Decorators need () even if no args [OK]
Hint: Always add () after decorators like @IsEmail() [OK]
Common Mistakes:
  • Forgetting parentheses on decorators
  • Changing property type incorrectly
  • Using wrong decorators for email
5. You want to create a DTO class CreateProductDto with these rules:
- title is a required string
- price is a required positive number
- description is an optional string
Which of the following DTO class definitions correctly implements these rules?
hard
A. import { IsString, IsNumber, IsPositive, IsOptional } from 'class-validator'; export class CreateProductDto { @IsString() title?: string; @IsNumber() @IsPositive() price?: number; @IsOptional() @IsString() description?: string; }
B. import { IsString, IsNumber, IsPositive, IsOptional } from 'class-validator'; export class CreateProductDto { @IsString() title: string; @IsNumber() @IsPositive() price: number; @IsOptional() @IsString() description?: string; }
C. import { IsString, IsNumber, IsPositive } from 'class-validator'; export class CreateProductDto { @IsString() title: string; @IsNumber() price: number; @IsString() description: string; }
D. import { IsString, IsNumber, IsPositive, IsOptional } from 'class-validator'; export class CreateProductDto { @IsString() title: string; @IsNumber() price: number; @IsOptional() description?: string; }

Solution

  1. Step 1: Check required string property

    Title is required string, so @IsString() with no @IsOptional() is correct.
  2. Step 2: Check required positive number property

    Price must be number and positive, so @IsNumber() and @IsPositive() are needed without @IsOptional().
  3. Step 3: Check optional string property

    Description is optional string, so @IsOptional() and @IsString() with optional property syntax (?) is correct.
  4. Final Answer:

    DTO with @IsString() title, @IsNumber() + @IsPositive() price, and optional @IsOptional() description -> Option B
  5. Quick Check:

    Required fields no @IsOptional(), optional fields with @IsOptional() [OK]
Hint: Use @IsOptional() only on optional fields [OK]
Common Mistakes:
  • Marking required fields as optional
  • Missing @IsPositive() for positive number
  • Omitting @IsOptional() on optional fields
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