How to properly wrap constructors with decorators in TypeScript

后端 未结 5 1986
猫巷女王i
猫巷女王i 2020-12-28 08:32

The process of wrapping a class with a decorator causes superclasses to be unable to access that classes\' properties. Why?

I have some code that:

  1. Crea
5条回答
  •  甜味超标
    2020-12-28 09:03

    This is the more modern approach using the latest TS (3.2.4). The below also uses the decorator factory pattern so you can pass in attributes:

    function DecoratorName(attr: any) {
      return function _DecoratorName(constr: T){
        return class extends constr {
          constructor(...args: any[]) {
            super(...args)
            console.log('Did something after the original constructor!')
            console.log('Here is my attribute!', attr.attrName)
          }
        }
      }
    }
    

    See here for more info: https://www.typescriptlang.org/docs/handbook/decorators.html#class-decorators

提交回复
热议问题