Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing typescript decorator dynamically

I have a field in a typescript class which has a decorator A, but i want change the decorator from A to B when it is running in some specific environment. Can this be achieved in typescript?

class SampleClass {
    @DecoratorA 
    sampleField;

    constructor() {
      if(condition) {
        // change DecoratorA to DecoratorB
      }
    }
}

Is it possible to change the DecoratorA to DecoratorB in the constructor based on some condition?

like image 865
Pavan Bahuguni Avatar asked Feb 24 '26 07:02

Pavan Bahuguni


1 Answers

So as suggested in comments create a decorator factory:

function AorB() {
    return condition ? DecoratorA : DecoratorB;
}

And apply it (pay attention to parentheses):

class SampleClass {
    @AorB() 
    sampleField;
}
like image 160
Aleksey L. Avatar answered Feb 26 '26 21:02

Aleksey L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!