I'm trying to implement a small caching function. While my implementation appears to work, I'm having a hard time defining the proper types in it.
type Producer<T> = (...args: any[]) => Promise<T>;
export function cache<T>(producer: Producer<T>): Producer<T> {
let cached;
return async function(...args: any[]): Promise<T> {
if (!cached) {
cached = await producer.apply(null, args);
}
return cached;
};
}
Yes, I still have to improve it, so that the value is cached based on the passed parameters, but that's a minor and easy to fix issue.
a Producer in this case is a function that can produce a cacheable value and should only ever be called once. cache() returns a function that should have matching parameters to the producer passed to the cache() function. Now, this works perfectly fine right now if you know what parameters to pass, but this is TypeScript, so I would love the compiler to be able to validate the types. I just don't know how to define that the returned function should have the same parameters as the producer. I know that there are all these utility types in TS, but I cannot figure out how to use them in this case.