Doar adăugând că , dacă încercați să adăugați defini ceva care este deja declarat, atunci aceasta este calea typesafe de a face acest lucru, care protejează de asemenea împotriva buggy for inimplementări.
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});
};
Care poate fi folosit pentru a polyfill în condiții de siguranță. Exemplu
//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);
}
Din păcate , nu se poate typecheck simbolurile din cauza unei limitare în TS actuale , și nu va țipa la tine dacă șirul nu se potrivește nici o definiție pentru un motiv oarecare, voi raporta bug - ul după ce a văzut , dacă sunt deja conștient.