代码之家  ›  专栏  ›  技术社区  ›  Jason Rogers

角度类装饰器函数对注释类不可见

  •  1
  • Jason Rogers  · 技术社区  · 4 年前

    我正在与一个装饰师合作,该装饰师使用额外的功能增强组件

    export function I18n(): ClassDecorator {
      return function (constructor: any) {
        constructor.prototype.interpolate = function (
          template: string,
          replacements: any
        ) {
          return service.interpolate(template, replacements);
        };
    
        constructor.prototype.stringForKeyPath = function (key: string) {
          return service.stringForKeyPath(key);
        };
      };
    }
    

    它用于组件中

    @I18n()
    export class AComponent implements OnInit {
    
       aMethod() {
          this.interpolate(templateString, replacements)
       }
    }
    

    或直接在模板中:

    {{ stringForKeyPath(aKey)}}
    

    当代码运行时,所有这些都可以正常工作

    但是Typescript错误,因为它不理解这些函数是由decorator类添加的

    如果我只是在中添加占位符 AComponent

    @I18n()
    export class AComponent implements OnInit {
       interpolate(a: string ,b)=>{return a}
    
       stringForKeyPath(a: string)=>{return a}
    
       aMethod() {
          this.interpolate(templateString, replacements)
       }
    }
    

    然后它就可以工作了,但它并不漂亮,必须将它添加到每个使用它的文件中

    如何为通过ClassDecorator添加的行为添加正确的类型?

    0 回复  |  直到 4 年前
    推荐文章