Απλά προσθέτοντας ότι εάν προσπαθείτε να προσθέσετε καθορίσει κάτι που έχει ήδη δηλωθεί, τότε αυτό είναι το typesafe τρόπος για να γίνει αυτό, που προστατεύει επίσης έναντι λάθη for inεφαρμογές.
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});
};
Ποια μπορεί να χρησιμοποιηθεί για να polyfill με ασφάλεια. Παράδειγμα
//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);
}
Δυστυχώς δεν μπορεί να typecheck Σύμβολα σας οφείλεται σε περιορισμό στην τρέχουσα TS , και δεν θα φωνάζω σε σας, αν το string δεν ταιριάζει με κανένα ορισμό για κάποιο λόγο, θα αναφέρετε το σφάλμα μετά από να δει αν είναι ήδη ενήμερος.