我有一个内存缓存函数,您可以向该函数传递一个函数及其参数,该函数将缓存结果.函数本身可以工作,但我不知道如何创建泛型类型签名,以便在使用函数而不是函数所需的参数调用缓存时出现错误.下面是一个最小的例子:
type AnyFunc = (...args: any[]) => any;
type MemCache<T extends AnyFunc> = {
(fn: T, ...args: Parameters<T>): ReturnType<T>;
debug: () => void;
};
function makeCache<T extends AnyFunc>(): MemCache<T> {
const cache = {};
function queryCache<T extends AnyFunc>(fn: T, ...args: Parameters<T>): ReturnType<T> {
return fn(...args)
}
queryCache.debug = () => {
console.log(cache)
};
return queryCache;
}
const memcache = makeCache()
const fn = (num: number, str: string) => 'hello'
//@ts-expect-error
const res = memcache(fn) // should error because 3 arguments are expected but received 1
//@ts-expect-error
res.then() // should error because fn returns a string, not a promise
你也可以在typescript playground中看到这个例子.
我已经try 提取内部函数(queryCache
),并按预期分别调用该函数和编译器错误.问题似乎出在外部函数上,但我需要它,因为在加载模块以实例化queryCache
函数关闭的缓存时会调用该函数.