Is it possible to pass Typescript decorator object values in at runtime?

一世执手 提交于 2019-12-13 21:56:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!