0

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?

1 Answer 1

1

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;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.