Typescript装饰器构造函数覆盖包括其他参数

ngf*_*ixl 3 constructor decorator typescript

根据typescript装饰器文档,替换构造函数的装饰器示例不会将任何参数传递给装饰器函数.我怎么能做到这一点?

这就是文档所说的

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

但我现在想传递像使用装饰器这样的参数,如下所示

@classDecorator({
  // some object properties fitting DecoratorData type
})
Run Code Online (Sandbox Code Playgroud)

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

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

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

Tit*_*mir 5

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)