假设我有一个简单的用例 - 我希望将一个函数包装在另一个时间跟踪函数中。我不想将时间跟踪代码复制粘贴到任何地方,而是想通过围绕原始函数创建一个包装函数并最终创建一个新函数来抽象时间跟踪代码。所以我最终得到了如下的函数。
function wrapFunction(someFunction: Function) {
const wrappedFunction = function() {
let args = arguments;
let beforeTime = new Date();
someFunction.apply(args);
let afterTime = new Date();
console.log("Time Elapsed " + afterTime - beforeTime);
};
return {execute: wrappedFunction};
}
然后要使用它,我会执行如下操作:
//Generate the wrapped function
let wrappedFunction = wrapFunction((param1 : string, param2: number) =>{
console.log("Param1 = ", param1);
console.log("Param2 = ", param2);
});
//This is the actual usage of the function
wrappedFunction.execute('param1', 2);
我的问题是:有没有一种方法可以动态设置返回的 .execute() 的函数参数,以便 Typescript 可以检测到错误,并且 IDE 可以获取函数参数。
在当前状态下,我无法在不检查函数生成位置的情况下检查应该传递哪些参数到 .execute() 中。
最佳答案
您可以在其余参数中使用泛型和元组:
function wrapFunction<A extends any[], R>(someFunction: (...a: A) => R) {
const wrappedFunction = function (...args: A) {
let beforeTime = new Date();
let result = someFunction(...args);
let afterTime = new Date();
console.log("Time Elapsed " + (afterTime.getDate() - beforeTime.getDate()));
return result;
};
return { execute: wrappedFunction };
}
//Generate the wrapped function
let wrappedFunction = wrapFunction((param1: string, param2: number) => {
console.log("Param1 = ", param1);
console.log("Param2 = ", param2);
});
wrappedFunction.execute('param1', 2); //ok now
关于javascript - 有没有办法在 Typescript 的包装函数中动态键入函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55105340/