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

问题描述 投票:3回答:1

根据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个回答
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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.