Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does prototype extend on typescript?

i extended function prototype but typescript doesn't recognize it.

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"))

result: tsc -e

The property 'proc' does not exist on value of type 'Function'

how do i extend this object?

like image 204
mizchi Avatar asked Oct 07 '12 04:10

mizchi


2 Answers

There is a Function interface in the standard typescript lib which declares the members of Function objects. You will need to declare proc as a member of that interface with your own add on like the following:

interface Function {
    proc(...args: any[]): any;
}

This interface will need to be referenced from anywhere you intend to use 'proc'.

like image 132
nxn Avatar answered Sep 21 '22 15:09

nxn


Like this:

declare global {
    interface Function {
        proc() : any;
    }
}

Without 'declare global' it doesn't work.

That's how module augmentation works in recent TypeScript versions. Check out the documentation and scroll down to the Module augmentation section.

like image 40
gaperton Avatar answered Sep 23 '22 15:09

gaperton