如何输入像_.once这样的东西

don*_*zul 3 typescript typescript-typings

刚开始使用TS,我该如何输入类似...

function once(fn) {
  var haveResult = false;
  var result = null;

  return (...args) => {
    if (!haveResult) {
      haveResult = true;
      result = fn.apply(this, args);
    }

    return result;
  };
}
Run Code Online (Sandbox Code Playgroud)

曾经可以接收任何参数的函数并返回任何参数.就像lodash的_.once一样

Tit*_*mir 5

您可以为函数类型使用泛型参数,并返回具有相同类型的新函数.不幸的是,由于每个参数都没有可变数量的类型参数,因此您需要使用类型断言来获取辅助函数以匹配结果类型,但调用站点将正确推断所有内容:

function once<TFunction extends (...args: any[])=> any>(fn: TFunction): TFunction {
    var haveResult = false;
    var result: any = null;

    return (function (this: any, ...args: any[]) {
        if (!haveResult) {
            haveResult = true;
            result = fn.apply(this, args);
        }

        return result;
    }) as any;
}
// Usage 
class Test {
    doStuff (t: string){
        console.log('doStuff');
        return  1;
    }

    constructor() {
        this.doStuff = once(this.doStuff);
    }
}

let t = new Test();
t.doStuff('s');
t.doStuff('s');
Run Code Online (Sandbox Code Playgroud)