function ensureGreaterThanZero(target: Object, propertyKey: string | symbol, parameterIndex: number) {
return function (target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
const param = args[parameterIndex];
if (typeof param!== 'number' || param <= 0) {
throw new Error('参数必须是大于0的数字');
}
return originalMethod.apply(this, args);
};
return descriptor;
};
}
class Example {
@ensureGreaterThanZero
someFunction(num: number) {
console.log(`接收到的数字: ${num}`);
}
}
const example = new Example();
example.someFunction(5);
// example.someFunction(-1); // 会抛出错误
装饰器作用解释
- 参数验证:在函数调用之前,装饰器可以拦截并检查传入函数的参数。在这个例子中,装饰器
ensureGreaterThanZero
确保了被装饰函数的特定位置参数(这里是第一个参数)是大于0的数字,否则抛出错误。
- 代码复用:通过将验证逻辑封装在装饰器中,可以在多个函数上复用同样的验证逻辑,提高代码的可维护性和复用性。如果验证逻辑发生变化,只需要修改装饰器代码,而不需要在每个使用该验证的函数中进行修改。
- 分离关注点:装饰器使得业务逻辑和验证逻辑分离。函数本身专注于其核心业务,而参数验证等辅助逻辑通过装饰器来实现,使代码结构更加清晰。