Reflect Metadata – An In-Depth Guide with APIs and Example Usage

Introduction to `reflect-metadata`

The `reflect-metadata` library is a powerful tool in TypeScript that enables advanced reflection abilities for JavaScript objects. It’s crucial for working with decorators and provides various APIs to facilitate metadata management. Below, we will explore key APIs with code examples and demonstrate how to use this library in a practical application.

Basic Setup

To install the `reflect-metadata` library, run the following command:

npm install reflect-metadata

Then, import the library at the start of your main file:

import "reflect-metadata";

Using Metadata APIs

Reflect.defineMetadata

This method defines metadata for a target object or property. Example:


 Reflect.defineMetadata("custom:annotation", "Hello World", MyClass.prototype, "myMethod");

Reflect.getMetadata

This method retrieves metadata from a target object or property. Example:


 const metadata = Reflect.getMetadata("custom:annotation", MyClass.prototype, "myMethod");
 console.log(metadata); // Hello World

Reflect.hasMetadata

This method checks if the target object or property has the specified metadata. Example:


 const hasMetadata = Reflect.hasMetadata("custom:annotation", MyClass.prototype, "myMethod");
 console.log(hasMetadata); // true

Reflect.deleteMetadata

This method deletes metadata from a target object or property. Example:


 Reflect.deleteMetadata("custom:annotation", MyClass.prototype, "myMethod");

Practical Application Example

Below is a practical example demonstrating the use of `reflect-metadata` in a class with decorators:

Creating a Logger Decorator


 function Log(target: any, propertyKey: string) {
  const originalMethod = target[propertyKey];

  target[propertyKey] = function (...args: any[]) {
   console.log(`Arguments: ${JSON.stringify(args)}`);
   const result = originalMethod.apply(this, args);
   console.log(`Result: ${result}`);
   return result;
  };

  Reflect.defineMetadata("log:enabled", true, target, propertyKey);
 }

Using the Logger Decorator


 class MyClass {
  @Log
  myMethod(arg1: string, arg2: number): number {
   return arg2;
  }
 }

 const myClassInstance = new MyClass();
 myClassInstance.myMethod("test", 42);
 // Console output:
 // Arguments: ["test",42]
 // Result: 42

Checking Metadata in the Application


 const hasLogMetadata = Reflect.hasMetadata("log:enabled", MyClass.prototype, "myMethod");
 console.log(`Is logging enabled: ${hasLogMetadata}`); // Is logging enabled: true

Conclusion

As demonstrated, `reflect-metadata` provides a rich API for metadata management which is particularly vital for decorators. By leveraging this library, developers can enhance their TypeScript applications with powerful reflection capabilities.

Hash: 4275c0b905603f64cb983d8d2d2f74d2ddea6f4559bdc4742be08bde91bd533e

Leave a Reply

Your email address will not be published. Required fields are marked *