Class decorator with different number of variables

Viewed 43

I want to create a decorator, that would override some variables, if they need to. Something like

const Decorator = <T extends { new (...args: any[]): any }>(target: T) => {
    return class extends target {
        field = 1;
        field2 = 2;
    };
};

But for one classes there should be only field, for others only field2, and some of them should be both.

I tried it, but it doesn't work

const Decorator = <T extends { new (...args: any[]): any }>(target: T) => {
    if (...) {
        target.prototype.field = 1;
    }
    if (...) {
        target.prototype.field2 = 2;
    }
    return class extends target {};
};
1 Answers

The thing that you return is just a class. So, make a constructor

const Decorator = <T extends { new (...args: any[]): any }>(target: T) => {
    return class extends target {
        constructor(...args1: any[]) {
            super(...args1);
            if (...) {
                this.field = 1;
            }
            if (...) {
                this.field2 = 2;
            }
        }
    };
};
Related