Decorator-based transformation, serialization, and deserialization of plain objects to class instances
Overview β’ Installation β’ Usage β’ Features β’ Development β’ Tech Stack
NFCtron Class Transformer is a TypeScript library that provides decorator-based transformation, serialization, and deserialization of plain JavaScript objects to class instances and vice versa. This is an NFCtron-maintained fork of the popular class-transformer library, published as @nfctron/class-transformer on GitHub Packages.
The library is essential for working with class-based models in TypeScript/JavaScript, especially when dealing with JSON data from APIs, databases, or configuration files. It allows you to transform plain objects into class instances with methods and getters, enabling proper object-oriented programming patterns.
- Object Transformation: Convert plain objects to class instances and vice versa
- Serialization/Deserialization: Transform objects for JSON serialization and deserialization
- Type Safety: Maintain TypeScript type safety during transformations
- Decorator-Based API: Use decorators to control transformation behavior
- Flexible Configuration: Control what properties are exposed, excluded, or transformed
npm install @nfctron/class-transformer reflect-metadatapnpm add @nfctron/class-transformer reflect-metadatayarn add @nfctron/class-transformer reflect-metadataThe reflect-metadata shim is required for this library to work. Make sure to import it in a global place in your application:
import 'reflect-metadata';For Node.js applications, add this import at the top of your main entry file (e.g., app.ts, index.ts).
For browser applications, add a script tag in your HTML:
<html>
<head>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
</head>
</html>Transform a plain object to a class instance:
import { plainToInstance } from '@nfctron/class-transformer';
import 'reflect-metadata';
class User {
id: number;
firstName: string;
lastName: string;
age: number;
getName() {
return this.firstName + ' ' + this.lastName;
}
isAdult() {
return this.age >= 18;
}
}
// Plain object from API/JSON
const userJson = {
id: 1,
firstName: 'John',
lastName: 'Doe',
age: 25,
};
// Transform to class instance
const user = plainToInstance(User, userJson);
// Now you can use class methods
console.log(user.getName()); // "John Doe"
console.log(user.isAdult()); // trueimport { instanceToPlain } from '@nfctron/class-transformer';
const user = new User();
user.id = 1;
user.firstName = 'John';
user.lastName = 'Doe';
// Transform to plain object for JSON serialization
const plainUser = instanceToPlain(user);
console.log(JSON.stringify(plainUser));const usersJson = [
{ id: 1, firstName: 'John', lastName: 'Doe' },
{ id: 2, firstName: 'Jane', lastName: 'Smith' },
];
const users = plainToInstance(User, usersJson);
// users is now User[] with all methods availableimport { Expose, instanceToPlain } from '@nfctron/class-transformer';
class User {
@Expose()
id: number;
@Expose()
email: string;
password: string; // Will be excluded
}
const user = new User();
user.id = 1;
user.email = 'user@example.com';
user.password = 'secret';
const plain = instanceToPlain(user);
// { id: 1, email: 'user@example.com' }import { Exclude } from '@nfctron/class-transformer';
class User {
id: number;
email: string;
@Exclude()
password: string;
}import { Type, plainToInstance } from '@nfctron/class-transformer';
class Photo {
id: number;
filename: string;
}
class Album {
id: number;
name: string;
@Type(() => Photo)
photos: Photo[];
}
const albumJson = {
id: 1,
name: 'Vacation',
photos: [
{ id: 1, filename: 'photo1.jpg' },
{ id: 2, filename: 'photo2.jpg' },
],
};
const album = plainToInstance(Album, albumJson);
// album.photos is now Photo[] with proper typesimport { Transform, Type } from '@nfctron/class-transformer';
class User {
id: number;
@Type(() => Date)
@Transform(({ value }) => value.toISOString(), { toPlainOnly: true })
createdAt: Date;
}- Groups: Control property exposure based on user roles or contexts
- Versioning: Expose different properties for different API versions
- Custom Transformers: Apply custom transformation logic
- Circular References: Handle circular object references
- Type Discriminators: Support for polymorphic types
- Implicit Type Conversion: Automatic type conversion (optional)
- Clone the repository:
git clone git@github.com:NFCtron/class-transformer.git
cd class-transformer- Install dependencies:
npm install
# or
pnpm install- Build the project:
npm run buildThis builds multiple output formats:
- CommonJS (
cjs/) - ES5 modules (
esm5/) - ES2015 modules (
esm2015/) - TypeScript types (
types/)
# Build all formats
npm run build
# Build specific formats
npm run build:cjs # CommonJS
npm run build:esm5 # ES5 modules
npm run build:esm2015 # ES2015 modules
npm run build:types # TypeScript definitions
npm run build:umd # UMD bundle
# Code quality
npm run lint:check # Check linting
npm run lint:fix # Fix linting issues
npm run prettier:check # Check formatting
npm run prettier:fix # Fix formatting
# Testing
npm test # Run tests with coverage
npm run test:watch # Watch mode
npm run test:ci # CI mode (no cache, run in band).
βββ src/ # Source code
β βββ ClassTransformer.ts # Main transformer class
β βββ decorators/ # Decorator implementations
β βββ interfaces/ # TypeScript interfaces
β βββ enums/ # Enumerations
β βββ utils/ # Utility functions
β βββ index.ts # Main entry point
βββ test/ # Test files
β βββ functional/ # Functional tests
βββ sample/ # Example code samples
βββ docs/ # Documentation
βββ tsconfig.json # TypeScript configuration
βββ package.json # Package configuration
# Run all tests
npm test
# Watch mode for development
npm run test:watch
# CI mode (for continuous integration)
npm run test:ci- Follow Conventional Commits for commit messages
- Use TypeScript for all code
- Run linting and formatting before committing
- Ensure all tests pass before submitting PRs
This package is published to GitHub Packages:
npm publishThe package is configured to publish to:
- Registry:
https://npm.pkg.github.com/ - Package name:
@nfctron/class-transformer
Versions follow Semantic Versioning:
- MAJOR: Breaking changes
- MINOR: New features (backward compatible)
- PATCH: Bug fixes (backward compatible)
- TypeScript: Programming language (v4.9.5)
- reflect-metadata: Runtime metadata reflection (required dependency)
- TypeScript Compiler: Multi-format compilation (CJS, ESM5, ESM2015)
- Rollup: UMD bundle generation
- Jest: Testing framework
- ESLint: Code linting
- Prettier: Code formatting
- Husky: Git hooks
- lint-staged: Pre-commit linting
- rimraf: Clean build directories
- class-validator - Often used together with class-transformer for validation
- nfctron-api - Uses this library for DTO transformations
- nfctron-cobra - Uses this library for data transformations
Main transformation methods:
plainToInstance<T, V>(cls: ClassConstructor<T>, plain: V, options?): T- Transform plain object to class instanceinstanceToPlain<T>(object: T, options?): Record<string, any>- Transform class instance to plain objectinstanceToInstance<T>(object: T, options?): T- Deep clone class instance
@Expose(options?)- Expose property during transformation@Exclude(options?)- Exclude property from transformation@Type(typeFn)- Specify nested object type@Transform(transformFn, options?)- Apply custom transformation
See the sample/ directory for comprehensive examples:
sample1-simple-usage/- Basic usage patternssample2-inheritance/- Working with class inheritancesample3-custom-arrays/- Custom array typessample4-generics/- Generic type handlingsample5-custom-transformer/- Custom transformation logic
- reflect-metadata Required: This library requires
reflect-metadatato be imported globally - ES6 Features: Uses ES6 classes and decorators
- TypeScript Decorators: Requires
experimentalDecoratorsandemitDecoratorMetadataintsconfig.json - Circular References: Handled automatically (ignored except in
instanceToInstance) - Performance: Optimized for production use with minimal overhead
- Decorator Metadata: Ensure
emitDecoratorMetadata: truein your TypeScript configuration - Runtime Performance: Transformation has minimal overhead but consider caching for high-frequency operations
- Type Safety: While TypeScript provides compile-time type checking, runtime validation may be needed
- Compatibility: Works with TypeScript 4.9+ and modern JavaScript runtimes
This is an NFCtron-maintained fork of typestack/class-transformer. Changes and improvements are maintained by the NFCtron team for internal use and published as @nfctron/class-transformer.