CodexBloom - Programming Q&A Platform

TypeScript class decorator not applying correctly to instance methods

👀 Views: 0 💬 Answers: 1 📅 Created: 2025-06-25
typescript decorators class TypeScript

I'm trying to debug I'm converting an old project and Hey everyone, I'm running into an issue that's driving me crazy. I'm having issues with a class decorator in TypeScript that I expect to modify the behavior of instance methods. I created a simple logger decorator to log the execution time of any method it decorates, but it seems to be affecting only the first method I apply it to. The second method logs the time, but the output is incorrect, as it seems to be showing the time from the first method instead. Here’s the decorator I wrote: ```typescript function LogExecutionTime(target: any, propertyKey: string, descriptor: PropertyDescriptor) { const originalMethod = descriptor.value; descriptor.value = function (...args: any[]) { const start = performance.now(); const result = originalMethod.apply(this, args); const end = performance.now(); console.log(`Execution time for ${propertyKey}: ${end - start} ms`); return result; }; } ``` And here’s how I’m using it in my class: ```typescript class MyClass { @LogExecutionTime methodOne() { // Simulating some work for (let i = 0; i < 1e6; i++) {} } @LogExecutionTime methodTwo() { // Simulating a different work for (let i = 0; i < 2e6; i++) {} } } ``` When I create an instance of `MyClass` and call `methodOne` and then `methodTwo`, the log for `methodTwo` shows the execution time from `methodOne`. Here's the console output I see: ``` Execution time for methodOne: 12 ms Execution time for methodTwo: 12 ms ``` I’ve tried moving the decorator above the class definition to see if that changes anything, but the same issue persists. I’ve also made sure to use the latest version of TypeScript (4.7.4). What am I missing here? Why doesn’t each method maintain its own execution context for logging? Any insights would be greatly appreciated! I'm working on a web app that needs to handle this. What's the best practice here? For context: I'm using Typescript on Linux. For reference, this is a production microservice. Could this be a known issue? What are your experiences with this?