Home > Enterprise >  Create new generic class in constructor of abstract class Typescript
Create new generic class in constructor of abstract class Typescript

Time:09-22

Can I create a new instance of a class in an abstract class constructor?

Something like this:

export abstract class BaseClass<T> {
  constructor(protected genericClass = new T());
}

Or is this just a real stupid question?

CodePudding user response:

It depends. In your example, because at runtime you do not have access to any type information, there is no way to know which class to instantiate. So without more information, it is not possible

The workaround for this is to supply the constructor. I'm not sure about the use, but here is how it could work:

export abstract class BaseClass<T> {
  constructor(cls: { new (): T }, protected genericClass = new cls()) {}
}

class MyClass {
  readonly value: number = 1;
}

class ExtendBaseClass extends BaseClass<MyClass> {
  constructor() {
    super(MyClass);
  }

  accessGenericClass() {
    return this.genericClass.value;
  }
}
  • Related