在运行时可以传递Typescript装饰器对象值吗? [英] Is it possible to pass Typescript decorator object values in at runtime?
问题描述
我有一个类使用@MinDate约束这样装饰:
I have a class that is decorated with a @MinDate constraint like this:
export default class Order {
purchaseDate: Date;
@MinDate(this.purchaseDate)
receiptDate: Date;
}
尝试验证 code>这是有效的验证错误。我的问题是将
this.purchaseDate
作为参数传递给 @MinDate()
装饰器。
When attempting to validate an instance of Order
that is valid the validation errors out. My question is is it even possible / valid to pass in this.purchaseDate
as an argument to the @MinDate()
decorator.
换句话说,可以从对象中获取运行时值,还是在编译时必须使用这些值?所以例如:
In other words can typescript decorators receive runtime values from an object, or do these values have to be available at compile time? So for example:
@MinDate(new Date(12/22/2017)); //This should work?
@MinDate(this.someDate) // This will never work?
推荐答案
不,你不能这样做。 >
装饰器应用于类而不是实例,这意味着调用装饰器函数时没有这个
。
No, you can't do that.
Decorators are applied to the classes and not the instances, meaning that there's no this
when the decorator function is invoked.
使用静态值将起作用:
@MinDate(new Date(12/22/2017));
但是您不能使用实例成员。
But you can't use an instance member for it.
您可以在没有装饰器的构造函数中执行此操作:
You can do that in the constructor without a decorator:
export default class Order {
...
constructor() {
this.purchaseDate = ...
this.receiptDate = this.purchaseDate;
}
}
这篇关于在运行时可以传递Typescript装饰器对象值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!