Can we change the constructor behavior using typescript class decorators? I mean to change number of parameters in constructor -


typescript code

@logclass // decorator class person {     public name: string;   public surname: string;    constructor(name : string, surname : string) {      this.name = name;     this.surname = surname;   } } function logclass(target: any) {    // save reference original constructor   var original = target;    // utility function generate instances of class   function construct(constructor, args) {     var c : = function () {       return constructor.apply(this, args);     }     c.prototype = constructor.prototype;     return new c();   }    // new constructor behaviour   var f : = function (...args) {     console.log("new: " + original.name);      return construct(original, args);   }    // copy prototype intanceof operator still works   f.prototype = original.prototype;    // return new constructor (will override original)   return f; } 

in above code new constructor adds console.log();. want change number of parameters passed constructor. possible? or can add other behavior? if so, please let me know?

you should able change arguments passed original constructor.

removing args:

var f : = function (...args) {     const level = args.shift();     console[level]("new: " + original.name);     return construct(original, args); } ... new person("debug", "name", "othername"); 

adding args:

var f : = function (...args) {     console.log("new: " + original.name);     if (args.length == 1) {         args.push("othername");     }     return construct(original, args); } ... new person("name"); 

the problem approach though it's not clear constructor signature happen, reads might think ctor accepts 2 arguments since decorator changes things break @ runtime.


edit

no, cannot change signature of constructor (or method/function) using decorator because static , being checked when complied, decorators can change things @ runtime.

my answer adding/removing arguments ctor done @ runtime, meaning while declared ctor person is:

constructor(name : string, surname : string) 

then doing this:

var f : = function (...args) {     const level = args.shift();     console[level]("new: " + original.name);     return construct(original, args); } 

creates new runtime ctor has following signature:

constructor(level: string, name : string, surname : string) 

it (again, @ runtime) removes first element in args, use level console , calls old ctor (the old declared signature) 2 args expects.


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -