【问题标题】:Typescript decorator constructor overwriting including additional arguments打字稿装饰器构造函数覆盖,包括附加参数
【发布时间】:2018-02-28 09:52:58
【问题描述】:

根据typescript decorators documentation,用于替换构造函数的装饰器示例不会将任何参数传递给装饰器函数。我怎样才能做到这一点?

医生是这么说的

function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
  return class extends constructor {
    newProperty = "new property";
    hello = "override";
  }
}

@classDecorator
class Greeter {
  property = "property";
  hello: string;
  constructor(m: string) {
    this.hello = m;
  }
}

但我现在想通过如下方式使用装饰器来传递参数

@classDecorator({
  // some object properties fitting DecoratorData type
})

我只是尝试添加第二个数据参数

function classDecorator<T extends {new(...args:any[]): {}}>(constructor: T, data: DecoratorData)

但这只是 tslint 需要 2 个参数,得到 1 个。插入 null 占位符也不起作用。我还尝试使用constructor 参数作为第二个可选参数。这会导致签名不匹配错误。

【问题讨论】:

    标签: typescript constructor decorator


    【解决方案1】:

    你需要使用一个装饰器生成器,一个返回装饰器函数的函数。生成器函数可以接受额外的参数,而内部装饰器函数可以捕获这些参数并使用它们。

    function classDecorator(data: DecoratorData) {
        return function <T extends { new(...args: any[]): {} }>(constructor: T) {
            return class extends constructor {
                newProperty = "new property";
                hello = "override";
                // use daat here 
            }
        }
    }
    
    @classDecorator({ data: "" })
    class Greeter {
        property = "property";
        hello: string;
        constructor(m: string) {
            this.hello = m;
        }
    }
    

    【讨论】:

    • 谢谢,它正在工作!属性被很好地覆盖。我是否能够在默认构造函数中访问新的构造函数属性,例如 newProperty
    • @ngfelixl 从类内部我不知道如何做到这一点(除了在Greeter 中声明字段并且已经由装饰器设置)。对于从外部访问,你不能使用装饰器,它们不会影响类的结构,但是你可以使用常规函数,看这个问题:stackoverflow.com/questions/48599889/…
    猜你喜欢
    • 2021-02-04
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 2015-12-12
    • 1970-01-01
    • 2016-04-11
    相关资源
    最近更新 更多