Gewoon toe te voegen dat als je probeert toe te voegen iets dat al is verklaard te definiëren, dan is dit de Typesafe manier om dit te doen, die ook bescherming biedt tegen buggy for inimplementaties.
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});
};
Die kan worden gebruikt om veilig Polyfill. Voorbeeld
//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);
}
Helaas kan het niet uw Symbols typecheck als gevolg van een beperking in de huidige TS , en het zal niet tegen je schreeuwen als de tekenreeks niet overeenkomt met een definitie voor een of andere reden, ik zal de bug na het zien te melden als ze al bewust.