Is it possible to generically restrict the argument of a method decorator based on the type of the method it is applied to?
I attempted to obtain the method's type that the decorator is applied to using
TypedPropertyDescriptor<Method>
. However, the type system did not raise any errors.
function MyCache<Method extends (...args: any[]) => Promise<any>>(keyFn: (...args: Parameters<Method>) => string) {
return function (target: object, methodName: string, descriptor: TypedPropertyDescriptor<Method>) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: Parameters<Method>) {
const cacheKey = keyFn(...args);
return originalMethod?.apply(this, args);
} as Method;
};
}
class CounterService {
// There should be an error because the function signature does not match the argument list of the method
@MyCache((id: string) => `test-${id}`)
async getCounter(config: { valid: boolean }, value: number): Promise<number> {
return 0;
}
}
Test it out here Typescript Playground