MST
星途 面试题库

面试题:TypeScript参数装饰器在简单函数参数验证中的应用

请使用TypeScript参数装饰器实现一个简单的函数参数验证功能,假设函数接受一个数字类型参数,装饰器用于确保传入的参数大于0。请给出完整的代码实现,并解释装饰器在这个场景中的作用。
34.1万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
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);  // 会抛出错误

装饰器作用解释

  1. 参数验证:在函数调用之前,装饰器可以拦截并检查传入函数的参数。在这个例子中,装饰器ensureGreaterThanZero确保了被装饰函数的特定位置参数(这里是第一个参数)是大于0的数字,否则抛出错误。
  2. 代码复用:通过将验证逻辑封装在装饰器中,可以在多个函数上复用同样的验证逻辑,提高代码的可维护性和复用性。如果验证逻辑发生变化,只需要修改装饰器代码,而不需要在每个使用该验证的函数中进行修改。
  3. 分离关注点:装饰器使得业务逻辑和验证逻辑分离。函数本身专注于其核心业务,而参数验证等辅助逻辑通过装饰器来实现,使代码结构更加清晰。