Web Development
TypeScript
Subjective
Oct 04, 2025
Explain advanced decorator patterns and metadata reflection.
Detailed Explanation
Decorators can store metadata using reflect-metadata library for dependency injection and validation.
Basic Decorator:
function Component(target: any) {
Reflect.defineMetadata('component', true, target);
}
@Component
class MyComponent {
// Implementation
}
Property Decorators:
function Inject(token: string) {
return function (target: any, propertyKey: string) {
Reflect.defineMetadata('inject', token, target, propertyKey);
};
}
class UserService {
@Inject('DATABASE')
private db: Database;
}
Method Decorators:
function Log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log('Calling method:', propertyKey);
return originalMethod.apply(this, args);
};
}
class Calculator {
@Log
add(a: number, b: number): number {
return a + b;
}
}
Metadata Reflection:
function getInjectionTokens(target: any): string[] {
const tokens: string[] = [];
const propertyKeys = Object.getOwnPropertyNames(target.prototype);
for (const key of propertyKeys) {
const token = Reflect.getMetadata('inject', target.prototype, key);
if (token) {
tokens.push(token);
}
}
return tokens;
}
Benefits:
• Enable dependency injection
• Provide runtime type information
• Support aspect-oriented programming
• Enable framework magic.
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts