mx_code
mx_code

Reputation: 2517

How to obtain constructor arguments inside a decorator?

I'm using angular/typescript.

How to obtain constructor arguments inside a decorator?

Following is a decorator function:

function ClassDecorator<T extends { new(...args: any[]): {} }>(constructor: T) {
    console.log("-- decorator function invoked --");
    return class extends constructor {

    }
}



and use it as :

@ClassDecorator()
export class SomeClass {
constructor(arg1) {} // ----> I want to access this arg1 inside the ClassDecorator
}

So my question is that is there a way to access the constructor (here arg1) arguments inside the @ClassDecorator ?

I've tried a bunch of solutions somewhat like the following:


export function ClassDec(ctor: Function) {
  ctor.prototype;
  console.log(' ctor.prototype :', ctor.prototype.arguments);
}


export function ClassDec(target: Function) {
  console.log(target.arguments);
  return (constructor: Function) => {
    console.log(constructor, target.arguments);
  };
}


// when I try to access the arguments of constructor function I'm getting an error saying cannot access arguments in strict mode.

But nothing is working out!

The idea is simple I want to receive the constructor(arg1) arguments inside the decorator function like this:

function ClassDecorator<T extends { new(...args: any[]): {} }>(constructor: T) {
    console.log("-- decorator function invoked --");

console.log(constructor.prototype.arguments)
    return class extends constructor {

    }
}



I know it's hard. I tried all online solutions. Just let me know whether this is possible or not. Else I can drop the plan.

Upvotes: 1

Views: 846

Answers (1)

SalientBrain
SalientBrain

Reputation: 2541

This works for me (like proxy):

    function ClassDecorator<T extends { new(...args: any[]): {} }>(constructor: T) {
        return class extends constructor {
            constructor(...args: any[]) {
                super(args);
                console.log(`Ctor arguments: ${args}`);
            }
        }
    }
    @ClassDecorator
    class SomeClass {
        constructor(arg1) {
    
        }
    }
    
    const a = new SomeClass("test");

Upvotes: 1

Related Questions