Basta aggiungendo che se si sta cercando di aggiungere definire qualcosa che è già dichiarato, allora questo è il modo typesafe di farlo, che protegge anche contro buggy for inimplementazioni.
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});
};
Il che può essere utilizzato per polyfill in modo sicuro. Esempio
//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);
}
Purtroppo non può TYPECHECK vostri simboli a causa di una limitazione nella TS attuali , e non sarà urlare a voi se la stringa non corrisponde alcuna definizione per qualche motivo, io segnalo il bug dopo aver visto se sono già consapevole.