我有很多这样的功能对象
const functionsObject = {
a: () => {/* does stuff */},
b: () => {/* does other stuff */},
}
我写了一个装饰器,记录了对任何这些功能的访问,但是我一直在努力正确地键入它。没有// @ts-ignore
,Typescript抱怨 type字符串不能用于索引T 类型。我理解为什么会这样说,但是我不知道该如何摆脱它。这是我的代码:
export const decorateWithLogging = <T extends { [functionName: string]: (...args: any) => any }> (functionObject: T) => {
for (const key of Object.keys(functionObject)) {
const fn = functionObject[key]
// @ts-ignore <--- ** I want to get rid of this **
functionObject[key] = function(...args: any) {
console.info('Calling function:', key)
return fn.call(this, ...args)
}
}
return functionObject
}