如何在 TypeScript 中为函数包装器添加类型?

How to add typings for a function wrapper in 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 函数类型,以便它适用于这两种情况?

您可以为 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>

(code in playground)