How To Use Decorators in TypeScript

In TypeScript, decorators provide a way to add both annotations and a meta-programming syntax for classes, methods, properties, or parameters. Decorators are functions that can be used to modify the behavior of these declarations.

Basic Decorator Syntax:

Here's a basic structure of a decorator function:

        
            function myDecorator(target: any, propertyKey: string) {
                // Modify behavior here
                console.log(`Decorating ${propertyKey} of ${target}`);
              }
              
              class MyClass {
                @myDecorator
                myMethod() {
                  // Method logic
                }
              }              
        
    

Types of Decorators:
  1. Class Decorators: Applied to classes.
  2. Method Decorators: Applied to methods within a class.
  3. Property Decorators: Applied to properties within a class.
  4. Parameter Decorators: Applied to constructor parameters within a class.
Example: Method Decorator

        
            function log(target: any, key: string, descriptor: PropertyDescriptor) {
                const originalMethod = descriptor.value;
              
                descriptor.value = function (...args: any[]) {
                  console.log(`Calling method ${key} with args: ${args}`);
                  return originalMethod.apply(this, args);
                };
              
                return descriptor;
              }
              
              class Example {
                @log
                greet(message: string) {
                  console.log(`Hello, ${message}!`);
                }
              }
              
              const instance = new Example();
              instance.greet('World');              
        
    

In this example:

  • log is a method decorator that intercepts the method execution.
  • descriptor.value contains the original method, and it's replaced with a wrapper function that logs before executing the original method.
Preparing TypeScript for Decorators:

To use decorators in TypeScript, ensure that:

  • "experimentalDecorators": true is set in your tsconfig.json file.
  • The TypeScript version supports decorators (which is generally the case in recent versions).
Notes on Decorators:
  • Decorators execute from top to bottom when a class is defined, not when instances are created.
  • They can accept arguments and return values, allowing them to be highly configurable.
  • They're useful for adding logging, validation, and other cross-cutting concerns without modifying the core logic of your classes or methods.

decorators are a powerful feature, but they require understanding their behavior and potential impacts on code execution and maintainability.

A Guide on Dependency Injection in NestJS

Dependency Injection (DI) is a design pattern that allows classes to define their dependencies without creating them. It's a fundamental concept in building scalable and maintainable applications. NestJS, being a TypeScript framework for building eff …

read more

How To Use Namespaces in TypeScript

In TypeScript, namespaces provide a way to organize code by encapsulating functionality within a named scope. Namespaces help prevent naming collisions and make it easier to structure larger codebases. Here's how you can use namespaces in TypeScript: …

read more