1

I have encountered an interesting problem. I have an abstract class with a static method that I want multiple other classes to extend.

I want to provide all of these uninstantiated classes as an array to a method in another class. This other classes method would instantiate them if the value returned from the class static method is false.

Here is some example code to illustrate my issue:

abstract class Abstract {
  public static defer() {
    return true;
  }
}

class MyClass extends Abstract {}

class OtherClass {
  public add(my_classes: Array<new () => Abstract>) {
    const x = my_classes[0].defer();
    const y = new my_classes[0]();
  }
}

const other_class = new OtherClass();
other_class.add([MyClass]);

On the line const x = my_classes[0].defer(); I get the following error:

Property 'defer' does not exist on type 'new () => Abstract'.ts(2339)

If I switch the my_classes param to have the type of Array<typeof Abstract> I get the following error when trying to instantiate it:

Cannot create an instance of an abstract class.(2511)

How do I call a static method in this circumstance and also be able to create a new instance of the class?

1 Answer 1

1

The type new () => Abstract represents just a function which can act as a constructor for the Abstract class. It does not capture the static members of Abstract since you could in theory create other classes which adhere to new () => Abstract but do not include any static members.

In typescript, you can access the static members using typeof Abstract. So change your definition of the add method to include both the constructor signature and the static methods:

public add(my_classes: Array<typeof Abstract & (new () => Abstract)>) { ... }

Which should correct your error.

Note that in typescript, the instance type of a class is just the same as the class name. In your example an instance of the Abstract class would have type Abstract. You access the static side of a class by prefixing with typeof.


Playground link.

Sign up to request clarification or add additional context in comments.

3 Comments

Your answer works for executing a static method, but fails when trying to instantiate the class. I edited the question to include this new information.
Try including the construction signature along with the static side of Abstract. Eg, change the type of your array elements from typeof Abstract to typeof Abstract & (new () => Abstract).
Genius. Thank you. If you update your answer to include that I'll mark it as the accepted answer.

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.