2016-11-12 72 views
0

我想寫的打字稿較小高速緩存包裝(簡體僞演示代碼):如何在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功能類型,因此它適用於兩種情況?

回答

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> 

code in playground

相關問題