Polymorphic call of this.constructor

265 Views Asked by At

WRONG QUESTION. EXAMPLE CODE WORKS.

Consider this code

export interface IParameterType{
  name:string,
  label:string,
  type:string,
  defaultValue:number
}

class Object3D{
  public static parameterTypes: IParameterType[] = [];
  constructor(){
    (this.constructor as typeof Object3D).parameterTypes.forEach(paramType => {
        console.log(paramType.name);
      });
  }

}

class Cube extends Object3D{
  public static parameterTypes: IParameterType[] = [
    {
      name: 'width',
      label: 'Width',
      type: 'integer',
      defaultValue: 10,
    },
    {
      name: 'height',
      label: 'Height',
      type: 'integer',
      defaultValue: 10,
    },
    {
      name: 'depth',
      label: 'Depth',
      type: 'integer',
      defaultValue: 10,
    },
  ];
}

class Sphere extends Object3D{
  public static parameterTypes: IParameterType[] = [
    {
      name: 'radius',
      label: 'radius',
      type: 'integer',
      defaultValue: 10,
    },
  ];
}

Problem is that (this.constructor as typeof Object3D).parameterTypes is not called polymorphically, I would like to call the parameterTypes of Cube or Sphere depending on the object instance.

In JavaScript this is straight forward: this.constructor.parameterTypesbut TypeScript does not allow me to do that -> Property 'parameterTypes' does not exist on type 'Function'

Any help?

I have tried:

if (this instanceof Cube){
      (this.constructor as typeof Cube).parameterTypes.forEach(paramType => {
        console.log(paramType.name!);
      });
    }

But doing so, what's the use of polymorphism?

0

There are 0 best solutions below