【问题标题】:Pass argument to class decorator将参数传递给类装饰器
【发布时间】:2018-08-24 21:28:52
【问题描述】:

我正在尝试使用 TypeScript 装饰器将具有动态值的属性添加到类中。 我使用 TS 文档中的以下代码:

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

这是可行的,但这些属性的值不是动态的。我们可以向这个函数传递一个参数吗?像这样:

@classDecorator('myArgument')

之后我想在 html 文件中使用myArgument

【问题讨论】:

    标签: angular typescript decorator


    【解决方案1】:

    装饰器是表达式,返回函数。表达式可以是函数名本身(我们像@classDecorator一样使用它),也可以是另一个函数的调用,它返回装饰器函数(然后我们像@classDecorator('myArgument')一样使用它)。第二种方法如下所示:

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

    【讨论】:

    • 好的,太好了,感谢您的帮助,这正是我想要的。 :)
    猜你喜欢
    • 2014-11-17
    • 2021-11-21
    • 2014-10-01
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 2022-07-12
    • 2020-05-16
    • 2021-01-19
    相关资源
    最近更新 更多