I had an idea to create a simple wrapper function using TypeScript. After some trial and error, I was able to make it work with the following code:
export function logFn<T extends (...args: any[]) => any>(
fn: T,
): (...args: Parameters<T>) => ReturnType<T> {
const log = (...args: Parameters<T>): ReturnType<T> => {
console.log('log')
return fn(...args)
}
return log
}
Although this solution works and satisfies the compiler, I originally attempted something that looked like this:
export function logFn<T extends (...args: any[]) => any>(
fn: T,
): T {
const log: T = (...args) => {
console.log('log')
return fn(...args)
}
return log
}
However, I encountered an error at the declaration of the log
variable with the message:
Type '(...args: any[]) => any' is not assignable to type 'T'.
'(...args: any[]) => any' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '(...args: any[]) => any'.
It seems there is a subtype relationship constraint at play that is causing confusion for me. I am hoping someone with a better understanding of this concept can provide an explanation that will help clarify things for me and reduce my confusion about this behavior (which I believe is correct).