Currently, I am in the process of creating a simple memoize
function. This function is designed to take another function and perform some behind-the-scenes magic by caching its return value. The catch is that the types for the returned function from memoize
should match exactly with the given function. However, I have encountered some errors that I am struggling to resolve. Interestingly, when I ignore these errors and proceed with using the function, it seems to work fine.
To illustrate my dilemma, I have created two functions. In my understanding, both types should be acceptable, but I am seeing more progress with the second implementation, although it still isn't functioning as expected.
You can test out the code on the TypeScript Playground. Just in case the link expires, here is a snapshot of the code alongside error screenshots:
function memoize1<F extends (...args: any[]) => Promise<any>>(func: F): F {
return (...args) => func(...args)
}
function memoize2<F extends (...args: any[]) => Promise<any>>(func: F): (...args: Parameters<F>) => ReturnType<F> {
return (...args) => func(...args)
}
const first = memoize1(() => {}) // Triggering complaints
const second = memoize1(async () => {}) // Works fine
const third = memoize2(() => {}) // Also triggering complaints
const fourth = memoize2(async () => {}) // Works like a charm
For reference, you can view the error images for the first example and the second example.