How to create an instance of a subclass from the super class?

The static method is called with its this value being the class object, the constructor of the subclass that you called it upon. So you can just instantiate that with new:

class Animal {
  static findOne() {
    return new this;
  }
}

class Human extends Animal{
}

class Dog extends Animal{
}

const human = Human.findOne() // returns a Human instance
const dog = Dog.findOne() // returns a Dog instance

Leave a Comment