How does prototype extend on typescript?

后端 未结 4 784
情歌与酒
情歌与酒 2020-12-06 09:48

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

Function.prototype.proc = function() {
  var args, target, v;
  var __slice = [].slice;
          


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-06 10:14

    I am adding this to advise against adding prototypes like the example shown in question since many people view this question. Add it as follows:

    interface Function {
        proc(...args: any[]): any;
    }
    
    Object.defineProperty(Function.prototype, 'proc', { value: function(arg: any[]) {
        // Your function body
    }});
    

    The reason is if you add it to the prototype directly, it could get enumerated if an instance of that function get's enumerated over. for i in ... Now this block could be in a code you do not control (recently happened to me), so it is best to keep your code as safe as possible.

提交回复
热议问题