Как обновить декоратор TypeScript ES5 Class, который переносит все методы на ES2015 / ES6? - PullRequest
0 голосов
/ 18 июня 2019

В ES5, чтобы украсить все методы класса, у меня был такой синтаксис:

export function validateArgs(constructor: Function) {
  // copy the methods so that we avoid self referencing.
  const original: Function = Object.assign({}, constructor);
  // iterate over all the static methods in the class
  for (const i in constructor) {
    // wrap them in a method that throws an error if args are not valid
    constructor[i] = function(...args: any[]) {
      if(areArgsValid(args)) {
           return original[i].apply(this, args);
      }
      throw `Args aren't valid`
    };
  }
}
@validateArgs
class Validator {
    static myThingIsValid(arg1) {
         return !!arg1;
    }
    myOtherThingIsValid(arg1) {
         return !!arg1;
    }
}

Когда я изменяю свой tsconfig на ES2015 с ES5, методы больше не заключаются в проверку аргументов.

1 Ответ

0 голосов
/ 18 июня 2019

В ES6 методы класса не перечисляются. В ES5 классы были скомпилированы в функции, и эти методы перечислимы. Поэтому после обновления следующие методы больше не повторяются:

for (const i in constructor) { ... }

Отсюда и частично решение: Получение списка статики для класса ES6

// clone the class
const original: Function = Object.assign( Object.create( Object.getPrototypeOf(constructor)), constructor);
Object.getOwnPropertyNames(constructor)
    .filter(prop => typeof prop === 'function')
    .forEach(val => {
        // copy the static method since it's not copied from the class clone
        original[i] = constructor[i];
        ....
    })

Однако это даст вам только статические методы. Чтобы получить все методы, вам нужно что-то вроде:

[
    ...Object.getOwnPropertyNames(constructor), 
    ...Object.getOwnPropertyNames(constructor.prototype)
]
.filter(prop => typeof (constructor[prop] || constructor.prototype[prop]) === 'function')
.forEach(val => ...)
...