Csak hozzátéve, hogy ha megpróbálja felvenni meghatározni valamit, ami már bejelentett, akkor ez a typesafe módja ennek, amely szintén véd a hibás for inmegvalósítások.
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});
};
Amelyeket fel lehet használni, hogy biztonságosan Polyfill. Példa
//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);
}
Sajnos ez nem typecheck a szimbólumok miatt korlátozás jelenlegi TS , és ez nem fog kiabálni, ha a húr nem egyezik meghatározása valamilyen okból, én a hiba bejelentése, miután látta, ha már tudatában.