What are Decorators?
Decorators provide a way to add both annotations and meta-programming syntax for class declarations and members.
Class Decorators
typescript
function Component(config: { selector: string }) {
return function<T extends { new (...args: any[]): {} }>(constructor: T) {
return class extends constructor {
selector = config.selector;
};
};
}
@Component({ selector: 'app-root' })
export class AppComponent {
constructor() {
console.log(this.selector); // 'app-root'
}
}Method Decorators
typescript
function Log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
console.log(`Calling ${propertyKey} with`, args);
const result = originalMethod.apply(this, args);
console.log(`Result:`, result);
return result;
};
}
class Calculator {
@Log
add(a: number, b: number) {
return a + b;
}
}Property Decorators
typescript
function MinLength(min: number) {
return function(target: any, propertyKey: string) {
let value: string;
const getter = () => value;
const setter = (newValue: string) => {
if (newValue.length < min) {
throw new Error(`${propertyKey} must be at least ${min} characters`);
}
value = newValue;
};
Object.defineProperty(target, propertyKey, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
};
}
class User {
@MinLength(3)
username!: string;
}Conclusion
Decorators provide powerful metaprogramming capabilities in TypeScript.