</>StackKit
</>StackKit

Developer tutorials & guides

black flat screen computer monitor
TypeScript

TypeScript decorators and metadata reflection

A comprehensive guide to TypeScript decorators and metadata reflection.

S
StackKit Team
May 12, 20264 min read
#typescript#tutorial#guide#decorators#advanced
{
  "title": "Unlocking the Power of TypeScript Decorators and Metadata Reflection",
  "description": "Learn how to use TypeScript decorators and metadata reflection to write more maintainable, efficient, and scalable code.",
  "content": "
# Unlocking the Power of TypeScript Decorators and Metadata Reflection
===========================================================

TypeScript decorators and metadata reflection are powerful features that can help you write more maintainable, efficient, and scalable code. In this article, we'll explore what decorators and metadata reflection are, how they work, and how you can use them to improve your code.

## What are TypeScript Decorators?
-------------------------------

TypeScript decorators are a design pattern that allows you to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it. They are a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter.

Here's an example of a simple decorator that logs a message to the console before calling the original function:

```typescript
function logDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;
  descriptor.value = function (...args: any[]) {
    console.log(`Calling ${propertyKey}`);
    return originalMethod.apply(this, args);
  };
  return descriptor;
}

class MyClass {
  @logDecorator
  myMethod() {
    console.log('Hello, world!');
  }
}

const obj = new MyClass();
obj.myMethod();
// Output:
// Calling myMethod
// Hello, world!

In this example, the logDecorator function is a decorator that takes the target object, property key, and property descriptor as arguments. It then overrides the original method with a new function that logs a message to the console before calling the original method.

What is Metadata Reflection?


Metadata reflection is a feature of TypeScript that allows you to access metadata about a class, method, or property at runtime. This metadata can include information such as the class name, method names, and property names.

Here's an example of how you can use metadata reflection to get the name of a class:

function classNameDecorator<T extends { new (...args: any[]): {} }>(constructor: T) {
  return class extends constructor {
    getClassName() {
      return constructor.name;
    }
  };
}

@classNameDecorator
class MyClass {}

const obj = new MyClass();
console.log(obj.getClassName()); // Output: MyClass

In this example, the classNameDecorator function is a decorator that takes a class constructor as an argument. It then returns a new class that extends the original class and adds a getClassName method that returns the name of the original class.

Using Decorators and Metadata Reflection Together


One of the most powerful use cases for decorators and metadata reflection is to use them together to implement aspect-oriented programming (AOP) concepts such as logging, authentication, and caching.

Here's an example of how you can use decorators and metadata reflection to implement a simple logging aspect:

function logDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;
  descriptor.value = function (...args: any[]) {
    console.log(`Calling ${propertyKey}`);
    const result = originalMethod.apply(this, args);
    console.log(`Returned from ${propertyKey}`);
    return result;
  };
  return descriptor;
}

function classNameDecorator<T extends { new (...args: any[]): {} }>(constructor: T) {
  return class extends constructor {
    getClassName() {
      return constructor.name;
    }
  };
}

@classNameDecorator
class MyClass {
  @logDecorator
  myMethod() {
    console.log('Hello, world!');
  }
}

const obj = new MyClass();
obj.myMethod();
// Output:
// Calling myMethod
// Hello, world!
// Returned from myMethod

In this example, the logDecorator function is a decorator that logs a message to the console before and after calling the original method. The classNameDecorator function is a decorator that adds a getClassName method to the class that returns the name of the class.

Conclusion


TypeScript decorators and metadata reflection are powerful features that can help you write more maintainable, efficient, and scalable code. By using decorators to extend the behavior of classes, methods, and properties, and metadata reflection to access metadata about classes, methods, and properties, you can implement aspect-oriented programming concepts such as logging, authentication, and caching. Whether you're building a small web application or a large enterprise system, decorators and metadata reflection are essential tools to have in your toolkit. " } ```

#typescript#tutorial#guide#decorators#advanced