DEV Community

Niraj Ratnawat
Niraj Ratnawat

Posted on

Understanding Decorators in TypeScript: A First-Principles Approach

Decorators in TypeScript provide a powerful mechanism for modifying the behavior of classes, methods, properties, and parameters. While they may seem like a modern convenience, decorators are rooted in the well-established decorator pattern found in object-oriented programming. By abstracting common functionality like logging, validation, or access control, decorators allow developers to write cleaner, more maintainable code.

In this article, we will explore decorators from first principles, break down their core functionality, and implement them from scratch. Along the way, we'll look at some real-world applications that showcase the utility of decorators in everyday TypeScript development.

What is a Decorator?

In TypeScript, a decorator is simply a function that can be attached to a class, method, property, or parameter. This function is executed at design time, giving you the ability to alter the behavior or structure of code before it runs. Decorators enable meta-programming, allowing us to add additional functionality without modifying the original logic.

Let's start with a simple example of a method decorator that logs when a method is called:



function log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;

  descriptor.value = function (...args: any[]) {
    console.log(`Calling ${propertyKey} with arguments: ${args}`);
    return originalMethod.apply(this, args);
  };

  return descriptor;
}

class Example {
  @log
  greet(name: string) {
    return `Hello, ${name}`;
  }
}

const example = new Example();
example.greet('John');


Enter fullscreen mode Exit fullscreen mode

Here, the log decorator wraps the greet method, logging its invocation and parameters before executing it. This pattern is useful for separating cross-cutting concerns like logging from the core logic.

How Decorators Work

Decorators in TypeScript are functions that take in metadata related to the item they are decorating. Based on this metadata (like class prototypes, method names, or property descriptors), decorators can modify behavior or even replace the decorated object.

Types of Decorators

Decorators can be applied to various targets, each with different purposes:

  • Class Decorators : A function that receives the constructor of the class.


function classDecorator(constructor: Function) {
  // Modify or extend the class constructor or prototype
}


Enter fullscreen mode Exit fullscreen mode
  • Method Decorators : A function that receives the target object, the method name, and the method’s descriptor.


function methodDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  // Modify the method's descriptor
}


Enter fullscreen mode Exit fullscreen mode
  • Property Decorators : A function that receives the target object and the property name.


function propertyDecorator(target: any, propertyKey: string) {
  // Modify the behavior of the property
}


Enter fullscreen mode Exit fullscreen mode
  • Parameter Decorators : A function that receives the target, the method name, and the index of the parameter.


function parameterDecorator(target: any, propertyKey: string, parameterIndex: number) {
  // Modify or inspect the method's parameter
}


Enter fullscreen mode Exit fullscreen mode

Passing Arguments to Decorators

One of the most powerful features of decorators is their ability to take arguments, allowing you to customize their behavior. For example, let’s create a method decorator that logs method calls conditionally based on an argument.



function logConditionally(shouldLog: boolean) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;

    descriptor.value = function (...args: any[]) {
      if (shouldLog) {
        console.log(`Calling ${propertyKey} with arguments: ${args}`);
      }
      return originalMethod.apply(this, args);
    };

    return descriptor;
  };
}

class Example {
  @logConditionally(true)
  greet(name: string) {
    return `Hello, ${name}`;
  }
}

const example = new Example();
example.greet('TypeScript Developer');


Enter fullscreen mode Exit fullscreen mode

By passing true to the logConditionally decorator, we ensure that the method logs its execution. If we pass false, the logging is skipped. This flexibility is key to making decorators versatile and reusable.

Real-World Applications of Decorators

Decorators have found practical use in many libraries and frameworks. Here are some notable examples that illustrate how decorators streamline complex functionality:

  • Validation in class-validator: In data-driven applications, validation is crucial. The class-validator package uses decorators to simplify the process of validating fields in TypeScript classes.


import { IsEmail, IsNotEmpty } from 'class-validator';

class User {
  @IsNotEmpty()
  name: string;

  @IsEmail()
  email: string;
}


Enter fullscreen mode Exit fullscreen mode

In this example, the @IsEmail and @IsNotEmpty decorators ensure that the email field is a valid email address and the name field is not empty. These decorators save time by eliminating the need for manual validation logic.

  • Object-Relational Mapping with TypeORM: Decorators are widely used in ORM frameworks like TypeORM to map TypeScript classes to database tables. This mapping is done declaratively using decorators.


import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  email: string;
}


Enter fullscreen mode Exit fullscreen mode

Here, @Entity, @Column, and @PrimaryGeneratedColumn define the structure of the User table. These decorators abstract away the complexity of SQL table creation, making the code more readable and maintainable.

  • Angular Dependency Injection: In Angular, decorators play a pivotal role in managing services and components. The @Injectable decorator marks a class as a service that can be injected into other components or services.


@Injectable({
  providedIn: 'root',
})
class UserService {
  constructor(private http: HttpClient) {}
}


Enter fullscreen mode Exit fullscreen mode

The @Injectable decorator in this case signals to Angular's dependency injection system that the UserService should be provided globally. This allows for seamless integration of services across the application.

Implementing Your Own Decorators: A Breakdown

Decorators are, at their core, just functions. Let’s break down the process of creating decorators from scratch:

Class Decorator

A class decorator receives the constructor of the class and can be used to modify the class prototype or even replace the constructor.



function AddTimestamp(constructor: Function) {
constructor.prototype.timestamp = new Date();
}

@AddTimestamp
class MyClass {
id: number;
constructor(id: number) {
this.id = id;
}
}

const instance = new MyClass(1);
console.log(instance.timestamp); // Outputs the current timestamp

Enter fullscreen mode Exit fullscreen mode




Method Decorator

A method decorator modifies the method descriptor, allowing you to alter the behavior of the method itself.



function logExecutionTime(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;

descriptor.value = function (...args: any[]) {
const start = performance.now();
const result = originalMethod.apply(this, args);
const end = performance.now();
console.log(</span><span class="p">${</span><span class="nx">propertyKey</span><span class="p">}</span><span class="s2"> executed in </span><span class="p">${</span><span class="nx">end</span> <span class="o">-</span> <span class="nx">start</span><span class="p">}</span><span class="s2">ms);
return result;
};

return descriptor;
}

class Service {
@logExecutionTime
execute() {
// Simulate work
for (let i = 0; i < 1e6; i++) {}
}
}

const service = new Service();
service.execute(); // Logs the execution time

Enter fullscreen mode Exit fullscreen mode




Property Decorator

A property decorator allows you to intercept property access and modification, which can be useful for tracking changes.



function trackChanges(target: any, propertyKey: string) {
let value = target[propertyKey];

const getter = () => value;
const setter = (newValue: any) => {
console.log(</span><span class="p">${</span><span class="nx">propertyKey</span><span class="p">}</span><span class="s2"> changed from </span><span class="p">${</span><span class="nx">value</span><span class="p">}</span><span class="s2"> to </span><span class="p">${</span><span class="nx">newValue</span><span class="p">}</span><span class="s2">);
value = newValue;
};

Object.defineProperty(target, propertyKey, {
get: getter,
set: setter,
});
}

class Product {
@trackChanges
price: number;

constructor(price: number) {
this.price = price;
}
}

const product = new Product(100);
product.price = 200; // Logs the change

Enter fullscreen mode Exit fullscreen mode




Conclusion

Decorators in TypeScript allow you to abstract and reuse functionality in a clean, declarative manner. Whether you're working with validation, ORMs, or dependency injection, decorators help reduce boilerplate and keep your code modular and maintainable. Understanding how they work from first principles makes it easier to leverage their full potential and craft custom solutions tailored to your application.

By taking a deeper look at the structure and real-world applications of decorators, you've now seen how they can simplify complex coding tasks and streamline code across various domains.

Top comments (0)