我正在尝试用typescript(简化的伪演示代码)编写一个小缓存包装器:
const cache = {};
export function cachify<T, V>(name:string, getFunction: (i:V)=>Promise<T>): (i:V) => Promise<T> {
return function() {
return cache[name] || getFunction.apply(this,arguments)
}
})
如果我的函数只有一个参数,例如
,这很有效function isNameFancy(name:string) {
return Promise.resolve(true)
}
const isNameFancyWithCache = cachify(isNameFancy)
然而,因为我指定i:V
这仅对一个参数有效。
如果我有第二个功能,例如isPersonFancy
它无法工作:
function isPersonFancy(personAge: number, personName: string) {
return Promise.resolve(true)
}
const isPersonFancyWithCache = cachify(isPersonFancy)
如何更改我的cachify函数类型以便它适用于这两种情况?
答案 0 :(得分:1)
您可以为cachify
函数声明其他签名:
const cache = {};
export function cachify<T, V>(name: string, getFunction: (i: V) => Promise<T>): (i: V) => Promise<T>;
export function cachify<T, V1, V2>(name: string, getFunction: (i: V1, j: V2) => Promise<T>): (i: V1, j: V2) => Promise<T>;
export function cachify(name: string, getFunction: (...args: any[]) => Promise<any>): (...args: any[]) => Promise<any> {
return function () {
return cache[name] || getFunction.apply(this,arguments)
}
};
function isNameFancy(name: string) {
return Promise.resolve(true)
}
const isNameFancyWithCache = cachify("isNameFancy", isNameFancy); // (i: string) => Promise<boolean>
function isPersonFancy(personAge: number, personName: string) {
return Promise.resolve(true)
}
const isPersonFancyWithCache = cachify("isPersonFancy", isPersonFancy); // (i: number, j: string) => Promise<boolean>