TS1241
Unable to resolve signature of method decorator when called as an expression.
Broken Code ❌
function CatchError(logMessage: string) {
return function (_target: any, descriptor: PropertyDescriptor) {
// Save a reference to the original method
const originalMethod = descriptor.value;
// Replace the method with a new function
descriptor.value = function (...args: any[]) {
try {
return originalMethod.apply(this, args);
} catch (error) {
console.error(logMessage, error);
}
};
};
}
class Example {
@CatchError('Error occurred in doSomething')
doSomething() {
throw new Error('I am failing!');
}
}
const example = new Example();
example.doSomething();This code throws an error because the decorator CatchError is missing the correct signature for the PropertyDescriptor.
Fixed Code ✔️
To fix this issue, update the signature for the decorator to include the _propertyKey parameter:
function CatchError(logMessage: string) {
return function (_target: any, _propertyKey: string | symbol, descriptor: PropertyDescriptor) {
// Save a reference to the original method
const originalMethod = descriptor.value;
// Replace the method with a new function
descriptor.value = function (...args: any[]) {
try {
return originalMethod.apply(this, args);
} catch (error) {
console.error(logMessage, error);
}
};
};
}
class Example {
@CatchError('Error occurred in doSomething')
doSomething() {
throw new Error('I am failing!');
}
}
const example = new Example();
example.doSomething();With this adjustment, the CatchError decorator now properly resolves the method signature, allowing you to catch and log errors as intended.
