MST
星途 面试题库

面试题:TypeScript方法装饰器实现日志记录

请使用TypeScript方法装饰器实现一个日志记录功能,要求在每次调用被装饰的类方法时,能够在控制台打印出方法名、传入的参数以及执行时间。同时,要考虑到如何处理异步方法。
12.5万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function logMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    descriptor.value = function(...args: any[]) {
        const methodName = propertyKey;
        const startTime = new Date().getTime();
        console.log(`开始调用方法 ${methodName},参数为:`, args);

        const result = originalMethod.apply(this, args);

        if (typeof result.then === 'function') {
            return result.then((res) => {
                const endTime = new Date().getTime();
                console.log(`方法 ${methodName} 执行完毕,耗时: ${endTime - startTime} ms`);
                return res;
            }).catch((err) => {
                const endTime = new Date().getTime();
                console.log(`方法 ${methodName} 执行出错,耗时: ${endTime - startTime} ms`);
                throw err;
            });
        } else {
            const endTime = new Date().getTime();
            console.log(`方法 ${methodName} 执行完毕,耗时: ${endTime - startTime} ms`);
            return result;
        }
    };
    return descriptor;
}

class MyClass {
    @logMethod
    async asyncMethod(param1: string, param2: number) {
        await new Promise(resolve => setTimeout(resolve, 1000));
        return `Async result: ${param1} - ${param2}`;
    }

    @logMethod
    syncMethod(param1: string, param2: number) {
        return `Sync result: ${param1} - ${param2}`;
    }
}

const myObj = new MyClass();
myObj.asyncMethod('test', 123).then(console.log);
console.log(myObj.syncMethod('test', 456));