class-transformer for TypeScript: A Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to class-transformer: what it is and why you need it

\n\n

class-transformer is a powerful library for TypeScript and JavaScript that allows you to transform plain JavaScript objects into class instances and vice versa. It solves a fundamental problem: when working with data from APIs, databases, or JSON files, you get simple objects without methods and types. class-transformer "brings to life" this data, turning it into full-fledged class objects with validation, transformation, and serialization.

\n\n

Main use cases:

\n
    \n
  • Transforming JSON from an API into typed class objects — for example, after receiving a response from a REST API, you can automatically transform the JSON into instances of your models.
  • \n
  • Data validation and transformation — using decorators, you can specify which fields are required and which need to be transformed (e.g., a string to a number or date).
  • \n
  • Serializing objects to JSON — the reverse transformation of class instances into plain objects for sending to the client or saving.
  • \n
  • Working with nested objects and arrays — the library can recursively transform nested data structures.
  • \n
\n\n

class-transformer is often used together with class-validator (for validation) and popular frameworks such as NestJS, TypeORM, and MikroORM.

\n\n

Installation

\n\n

The library is installed via npm or yarn:

\n\n
npm install class-transformer --save
\n\n

Or, if you are using yarn:

\n\n
yarn add class-transformer
\n\n

To work with decorators in TypeScript, you need to enable support for experimental decorators in the tsconfig.json file:

\n\n
{\n  "compilerOptions": {\n    "experimentalDecorators": true,\n    "emitDecoratorMetadata": true\n  }\n}
\n\n

It is also recommended to install reflect-metadata for proper decorator functionality:

\n\n
npm install reflect-metadata --save
\n\n

And import it at the very beginning of your application (usually in the main file index.ts or main.ts):

\n\n
import 'reflect-metadata';
\n\n

Quick start with a code example

\n\n

Let's create a simple user model and transform JSON data into a class instance.

\n\n
import { plainToClass, Expose, Type } from 'class-transformer';\nimport 'reflect-metadata';\n\n// Define the User class\nclass User {\n    @Expose()\n    id: number;\n\n    @Expose()\n    firstName: string;\n\n    @Expose()\n    lastName: string;\n\n    @Expose()\n    @Type(() => Date)\n    createdAt: Date;\n\n    // Class method — only available after transformation\n    getFullName(): string {\n        return `${this.firstName} ${this.lastName}`;\n    }\n}\n\n// Example data from an API (plain object)\nconst plainUser = {\n    id: 1,\n    firstName: 'Ivan',\n    lastName: 'Petrov',\n    createdAt: '2024-01-15T10:30:00Z'\n};\n\n// Transform the plain object into an instance of the User class\nconst userInstance = plainToClass(User, plainUser);\n\nconsole.log(userInstance instanceof User); // true\nconsole.log(userInstance.getFullName());   // "Ivan Petrov"\nconsole.log(userInstance.createdAt);       // Date object: Tue Jan 15 2024 13:30:00 GMT+0300\n
\n\n

As you can see, we got a full-fledged class object with methods and correctly transformed types (the date string became a Date object).

\n\n

Main methods and functions of class-transformer

\n\n

1. plainToClass

\n

What it does: Transforms one or more plain objects into instances of a class.

Recommendations