代码之家  ›  专栏  ›  技术社区  ›  Felix Lemke

Typescript装饰器构造函数覆盖,包括附加参数

  •  4
  • Felix Lemke  · 技术社区  · 8 年前

    根据 typescript decorators documentation 替换构造函数的decorator示例不会将任何参数传递给decorator函数。我如何才能做到这一点?

    医生是这么说的

    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;
      }
    }
    

    但我现在想传递如下参数,比如使用decorator

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

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

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

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

    1 回复  |  直到 8 年前
        1
  •  7
  •   Titian Cernicova-Dragomir    8 年前

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

    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;
        }
    }