问题
I have a class that is decorated with a @MinDate constraint like this:
export default class Order {
purchaseDate: Date;
@MinDate(this.purchaseDate)
receiptDate: Date;
}
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?
回答1:
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.
Using a static value will work:
@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;
}
}
来源:https://stackoverflow.com/questions/43742615/is-it-possible-to-pass-typescript-decorator-object-values-in-at-runtime