Transforming Payloads

With transform enabled, ValidationPipe turns plain JSON into typed DTO instances and converts primitives.

Syntax@Type(() => Number)

By default, request data arrives as plain objects and strings. With transform: true, the ValidationPipe uses class-transformer to convert payloads into real instances of your DTO classes.

What transformation does

  • Creates an actual CreateUserDto instance, so its methods are available.
  • Converts route and query params to their declared types (e.g. string to number).
  • Applies @Type() hints for nested objects and arrays.

Use @Type(() => Number) from class-transformer when you need explicit conversion of a value.

Example

Example Β· typescript
import { Type } from 'class-transformer';
import { IsInt, Min } from 'class-validator';

export class PaginationDto {
  @Type(() => Number) // convert the query string to a number
  @IsInt()
  @Min(1)
  page: number;
}

When to use it

  • A developer enables transform:true so a route parameter :id received as a string "42" is automatically cast to a number before the handler runs.
  • A team uses @Type(() => Number) on a DTO property so JSON strings from form submissions are coerced to numbers during deserialization.
  • An engineer uses class-transformer's @Exclude() to strip sensitive fields (like password hashes) from response objects before serialization.

More examples

Auto-transform query to number

Uses @Type(() => Number) to coerce query string values to integers, enabling typed query DTOs with default values.

Example Β· ts
import { IsInt, Min } from 'class-validator';
import { Type } from 'class-transformer';

export class PaginationDto {
  @Type(() => Number)   // '10' β†’ 10
  @IsInt()
  @Min(1)
  page: number = 1;

  @Type(() => Number)
  @IsInt()
  @Min(1)
  limit: number = 20;
}

Exclude sensitive property

Marks a field with @Exclude so class-transformer omits it when the object is serialized in the response.

Example Β· ts
import { Exclude } from 'class-transformer';

export class UserResponseDto {
  id: number;
  name: string;
  email: string;

  @Exclude()   // never serialized in the response
  passwordHash: string;

  constructor(partial: Partial<UserResponseDto>) {
    Object.assign(this, partial);
  }
}

ClassSerializerInterceptor + @Expose

Applies ClassSerializerInterceptor so @Exclude and @Expose decorators on UserResponseDto are honoured automatically.

Example Β· ts
import { Controller, Get, UseInterceptors, ClassSerializerInterceptor } from '@nestjs/common';

@Controller('users')
@UseInterceptors(ClassSerializerInterceptor)
export class UsersController {
  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number): UserResponseDto {
    return new UserResponseDto({ id, name: 'Alice', passwordHash: 'secret' });
  }
}

Discussion

  • Be the first to comment on this lesson.