The following code is working in the TS playground, but doesnt seem to work with the same config settings in my actual project.
Code:
class Test {
@loggedMethod
private async sayHi(txt: string) {
console.log(txt);
}
async difMethod() {
this.sayHi('well');
}
}
function loggedMethod(originalMethod: any, context: ClassMethodDecoratorContext) {
const methodName = String(context.name);
function replacementMethod(this: any, ...args: any[]) {
console.log(`LOG: Entering method '${methodName}'.`);
const result = originalMethod.call(this, ...args);
console.log(`LOG: Exiting method '${methodName}'.`);
return result;
}
return replacementMethod;
}
const tClass = new Test();
tClass.difMethod();
ts.config (local)
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"experimentalDecorators": true,
"suppressImplicitAnyIndexErrors": true,
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}
On the other hand, the following does work in my actual project
class Test {
@loggedMethod
private async sayHi(txt: string) {
console.log(txt);
}
async difMethod() {
this.sayHi('well');
}
}
function loggedMethod(target: any, name: string, descriptor: PropertyDescriptor) {
target[name] = function replacementMethod(this: any, ...args: any[]) {
console.log(`LOG: Entering method '${name}'.`);
const result = descriptor.value?.call(this, ...args);
console.log(`LOG: Exiting method '${name}'.`);
return result;
};
return target[name];
}
const tClass = new Test();
tClass.difMethod();
Notice the difference in the arguments for the decorator function. Why the difference? Both are set to TS 5.4.5 and it does work for the second version when I remove the "experimentalDecorators": true,
However, when I do remove "experimentalDecorators": true,
I get an error Unable to resolve signature of method decorator when called as an expression. The runtime will invoke the decorator with 2 arguments, but the decorator expects 3.
Which would reflect the documentation of TS5.x decorators as shown https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/#decorators
in the number of arguments, but it seems that, regardless of my "experimentalDecorators": true,
option, it is using the old decorator definition. Is there another config somewhere?