What is the reflect-metadata library in TypeScript?
The reflect-metadata
library is used to enable metadata reflection in TypeScript. It allows decorators to access metadata about classes, properties, methods, or parameters.
import "reflect-metadata";
// Define a decorator to add metadata to a class
function MyDecorator(target: Function) {
// Attach metadata to the class constructor
Reflect.defineMetadata("customMetadata", { description: "This is a custom decorator" }, target);
}
@MyDecorator
class Example {
constructor(public name: string) {}
}
// Retrieve metadata from the Example class
const metadata = Reflect.getMetadata("customMetadata", Example);
console.log(metadata);
// { description: 'This is a custom decorator' }