javascript - 有没有办法在 Typescript 的包装函数中动态键入函数?

标签 javascript typescript function types metaprogramming

假设我有一个简单的用例 - 我希望将一个函数包装在另一个时间跟踪函数中。我不想将时间跟踪代码复制粘贴到任何地方,而是想通过围绕原始函数创建一个包装函数并最终创建一个新函数来抽象时间跟踪代码。所以我最终得到了如下的函数。

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/

相关文章:

javascript - vis.js : How to expand/collapse nodes with mouse click

javascript - 从 ExtJS 6.6 href 链接运行 Controller 功能

javascript - 如何使用 2 个独立的数据库,一个用于写入端,一个用于读取端。 (两个数据库通过eventbus同步)

PHP 自动加载和函数中的静态变量

Javascript 跳过函数

javascript - 根据子事件查找父元素

javascript - 如何在 Kaltura 的 HTML5 媒体播放器中禁用全屏模式?

javascript - Fullcalendar + Angular 6 和 jQuery : TS2304: Cannot find name 'JQueryPromise'

angular - typescript 错误 : Property 'files' does not exist on type 'HTMLElement'

javascript - setInterval() 同时执行的两个函数会互相减慢