Accessing static member of generic class from a decorator

Viewed 1230

I have a decorated class:

@Decorator
class Entity {
    public static member: string[] = [];
}

With a decorator:

function Decorator<T extends { new(...args: any[]): Entity }>(constructor: T) {
  return class extends constructor {
    constructor(...args: any[]) {
      super(...args);
      // Do some things
      constructor.prototype.member.map((v: string) => {
        // Do things with the elements of the static array.
      });
    }
  };
}

Although this works, by using constructor.prototypewhich is of type any I lose the typechecking of member that is already in the prototype as an array of strings.

Is there a solution without losing the typechecking?

Edit: I've tested also:

function Decorator<T extends { prototype: typeof Entity; new(...args: any[]): Entity; }>(constructor: T) {
  return class extends constructor {
    constructor(...args: any[]) {
      super(...args);
      // Do some things
      constructor.prototype.member.map((v) => {
        // Do things with the elements of the static array.
      });
    }
  };
}

but this gives an error in the line @Decorator:

Property 'prototype' is missing in type 'Entity'.'

Edit2: I've tested too:

function Decorator<T extends typeof Entity>(constructor: T) {
  // This works and returns an Entity.
  const x = new constructor({} as any);
  // This doesn't work. Tsc says: 'Type 'T' is not a constructor function type.'
  return class extends constructor {
    constructor(...args: any[]) {
      super(...args);
      // This now works:  
      constructor.member.map((v) => {
        // ...
      });
    }
  };
}

but this gives an error in the line @Decorator:

Property 'prototype' is missing in type 'Entity'.'

1 Answers
Related