I was playing with the idea of a simple wrapper function using TypeScript. I ended up getting something working with the following:
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
}
This works and the compiler is happy. My question is around my initial attempt which looked more 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
}
This was giving me an error at the log
variable declaration with the error:
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 that there's some subtype relationship constraint that I can't fully wrap my head around (this error isn't doing me too many favors either). Was hoping someone with a better mental grasp on this stuff could give me a decent explanation so I can be less confused by this behavior (which I'm sure is correct).