fe-interview
                                
                                
                                
                                    fe-interview copied to clipboard
                            
                            
                            
                        [TypeScript] 第1514天 在TypeScript中装饰器有哪些应用场景?
TypeScript 中的装饰器是一种特殊的声明,它能够附加到类声明、方法、访问符、属性或参数上,用于修改类的行为。装饰器在应用开发中有很多场景,特别是在元编程、依赖注入、日志记录、验证和缓存等方面。以下是一些常见的装饰器应用场景(常见场景见 https://github.com/haizlin/fe-interview/issues/5508 )和示例:
1. 依赖注入
装饰器可以用于实现依赖注入,常用于 Angular 和 NestJS 等框架。
示例:
function Injectable(constructor: Function) {
    // 注册依赖
}
@Injectable
class Service {
    getService() {
        return "Service Called";
    }
}
@Injectable
class Component {
    constructor(private service: Service) {}
    callService() {
        console.log(this.service.getService());
    }
}
const service = new Service();
const component = new Component(service);
component.callService(); // 输出: Service Called
2. 验证和权限检查
装饰器可以用于验证输入数据或检查用户权限。
示例:
function validate(target: any, propertyName: string, descriptor: PropertyDescriptor) {
    const method = descriptor.value;
    descriptor.value = function(...args: any[]) {
        if (args.some(arg => arg == null)) {
            throw new Error("Invalid arguments");
        }
        return method.apply(this, args);
    };
}
class User {
    @validate
    updateUser(name: string, age: number) {
        console.log(`Updating user with name: ${name} and age: ${age}`);
    }
}
const user = new User();
user.updateUser("John", 30); // 输出: Updating user with name: John and age: 30
// user.updateUser("John", null); // 抛出错误: Invalid arguments
总结
TypeScript 中的装饰器是一种元编程工具,允许开发者在类声明、方法、访问符、属性和参数上附加自定义逻辑。它们在各种应用场景中非常有用,包括依赖注入、日志记录、验证和权限检查等。通过使用装饰器,开发者可以编写更加简洁和可维护的代码。