Wystarczy dodać, że jeśli próbujesz dodać określić coś, co już zadeklarowane, to jest to typesafe sposób robić to, że chroni również przed wadliwymi for inimplementacjami.
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});
};
Które mogą być wykorzystane do bezpiecznego PolyFill. Przykład
//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);
}
Niestety nie można typecheck swoje Symbole ze względu na ograniczenia w obecnych TS , i nie będzie krzyczeć na ciebie, jeśli ciąg nie pasuje do żadnej definicji z jakiegoś powodu, będę zgłosić błąd po obejrzeniu jeśli już jesteś świadomy.