MST
星途 面试题库

面试题:TypeScript 装饰器实现复杂 AOP 场景

假设存在一个类,类中有多个方法。使用 TypeScript 装饰器实现 AOP,当类中任意方法被调用时,如果方法参数之和大于100,记录此次调用信息(包括方法名和参数)到控制台。请写出具体实现代码。
11.9万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function logIfParamsSumGT100(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    descriptor.value = function(...args: number[]) {
        const sum = args.reduce((acc, val) => acc + val, 0);
        if (sum > 100) {
            console.log(`Method ${propertyKey} called with args: ${args}`);
        }
        return originalMethod.apply(this, args);
    };
    return descriptor;
}

class MyClass {
    @logIfParamsSumGT100
    method1(a: number, b: number) {
        return a + b;
    }

    @logIfParamsSumGT100
    method2(c: number, d: number, e: number) {
        return c + d + e;
    }
}

const myClass = new MyClass();
myClass.method1(50, 60);
myClass.method2(30, 40, 20);