Extending Object.prototype with TypeScript

后端 未结 3 1940
野的像风
野的像风 2020-12-09 14:59

I am currently working on a TypeScript API, which requires some additional features binding to the Object prototype (Object.prototype).

Consider the following code:<

3条回答
  •  时光取名叫无心
    2020-12-09 16:03

    I have extended the Array the same way and faced a big problem when s a party was using for i in ... to loop over it. Now you can't control every third party code and these bugs could get really annoying so I suggest a better aprocach:

    interface Array {
       crandom(): T;
    }
    
    /** Retrieve a random element from the list */
     Object.defineProperty(Array.prototype, 'crandom', { value: function() {
    
        let index = Math.floor(Math.random() * this.length);
    
        return this[index];
    }
    });
    

    Now by using Object.defineProperty your new property won't be enumerated over and it is safe. The above code pretty much gives a random element from the array. I made another one too which pops a random element from array:

    Object.defineProperty(Array.prototype, 'popRandom', { value: function() {
    
        let index = Math.floor(Math.random() * this.length);
    
        let result = this[index];
        this.splice(index, 1);
    
        return result;
    }
    });
    

    with Object.defineProperty You get more control over this creation and you can add additional restrictions too.

提交回复
热议问题