Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 495
Ole Avatar asked Feb 05 '23 13:02

Ole


1 Answers

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;
    }
}
like image 177
Nitzan Tomer Avatar answered Feb 18 '23 21:02

Nitzan Tomer