Jen s tím, že pokud se snažíte přidat definovat něco, co již deklarovanou, pak je to typesafe způsob, jak dělat tak, že také chrání před buggy for inimplementacemi.
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});
};
Které mohou být použity k bezpečnému polyfill. Příklad
//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);
}
Bohužel to nelze typecheck své symboly kvůli omezením v běžných TS , a to nebude křičet na vás, pokud řetězec neodpovídá žádnou definici z nějakého důvodu, budu hlásit chybu poté, co viděl, jestli už jsou vědomi.