Просто добавив , что если вы пытаетесь добавить определить то , что уже объявлено, то это типизированный способ сделать так, что также защищает от багги 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 , и он не будет кричать на вас , если строка не соответствует ни одному определения по какой - то причине, я сообщить об ошибке после просмотра , если они уже осознанный.