Simplemente añadiendo que si usted está tratando de añadir a definir algo que ya se declaró, entonces esta es la manera de hacerlo typesafe, que también protege contra cochecillo for inimplementaciones.
export const augment = <U extends (string|symbol), T extends {[key :string] :any}>(
type :new (...args :any[]) => T,
name :U,
value :U extends string ? T[U] : any
) => {
Object.defineProperty(type.prototype, name, {writable:true, enumerable:false, value});
};
Que puede ser utilizado para polyfill segura. Ejemplo
//IE doesn't have NodeList.forEach()
if (!NodeList.prototype.forEach) {
//this errors, we forgot about index & thisArg!
const broken = function(this :NodeList, func :(node :Node, list :NodeList) => void) {
for (const node of this) {
func(node, this);
}
};
augment(NodeList, 'forEach', broken);
//better!
const fixed = function(this :NodeList, func :(node :Node, index :number, list :NodeList) => void, thisArg :any) {
let index = 0;
for (const node of this) {
func.call(thisArg, node, index++, this);
}
};
augment(NodeList, 'forEach', fixed);
}
Por desgracia, no puede typecheck sus símbolos debido a una limitación en el TS actuales , y no va a gritarte si la cadena no coincide con ninguna definición, por alguna razón, voy a informar el error después de ver si ya están consciente.