原型如何在打字稿上扩展?

miz*_*chi 18 javascript typescript

我扩展了函数原型但是typescript无法识别它.

Function.prototype.proc = function() {
  var args, target, v;
  var __slice = [].slice;
  args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
  target = this;
  while (v = args.shift()) {
    target = target(v);
  }
  return target;
};
// generated by coffee-script

var foo: (number) => (string) => number
  = (a) => (b) => a * b.length;
console.log(foo.proc("first", "second"))
Run Code Online (Sandbox Code Playgroud)

结果:tsc -e

The property 'proc' does not exist on value of type 'Function'
Run Code Online (Sandbox Code Playgroud)

我该如何扩展这个对象?

nxn*_*nxn 33

标准typescript lib中有一个Function接口,用于声明Function对象的成员.您将需要将proc声明为该接口的成员,并使用您自己的add,如下所示:

interface Function {
    proc(...args: any[]): any;
}
Run Code Online (Sandbox Code Playgroud)

需要在您打算使用'proc'的任何地方引用此接口.


gap*_*ton 12

像这样:

declare global {
    interface Function {
        proc() : any;
    }
}
Run Code Online (Sandbox Code Playgroud)

没有'声明全球',它就不起作用.

这就是模块扩充在最近的TypeScript版本中的工作原理.查看文档并向下滚动到该Module augmentation部分.