0

I want to extend a class by only adding a new (non static) function, without changing the constructor. My super class can only be constructed from a static function. Now, when I construct my sub class with that static function, I receive an object that is an instance of the super class although I want the sub class. What can I do to achieve what I am looking for without changing the super class?

Here is a minimal example:

class MySuperClass {
    static staticConstructor() {
        return new MySuperClass()
    }
}

class MySubClass extends MySuperClass {
    addedFunction() {}
}

const mySuperClass = MySuperClass.staticConstructor()
console.log(mySuperClass instanceof MySuperClass) // true

const mySubClass = MySubClass.staticConstructor()
console.log(mySubClass instanceof MySubClass) // false, I want this to be true
console.log(mySubClass instanceof MySuperClass) // true

// calling mySubClass.addedFunction results in an error due to wrong instance

PS: I could not find a solution here but I am quite sure there should be one. Every search resulted in some DOM manipulation that I am obviously not looking for.

wfreude
  • 492
  • 3
  • 10
  • 1
    The `staticConstructor` should use `return new this()` – Bergi Feb 03 '20 at 09:27
  • Damn I feel dumb. Thank you, that helped! Do you know how to properly type the return value of staticConstructor in Typescript? I guess this will only be correct for my subclass using Generics or any? – wfreude Feb 03 '20 at 09:33
  • 1
    Yes, I suspect you need generics for that. There are a few TypeScript issues related to this, e.g. https://github.com/Microsoft/TypeScript/issues/18685 – Bergi Feb 03 '20 at 09:37

1 Answers1

1

Your problem is due to the fact that your static constructor will always return an instance of the SuperClass whatever subclasses you may create. For your second console.log to return true, you need to replace the static constructor code by return new this()

Raekh Void
  • 441
  • 3
  • 11
  • Thank you. Do you know how I would properly type the return value of the `staticConstructor` in Typescript? Is this only achievable by using Generics? – wfreude Feb 03 '20 at 09:35
  • What do you mean by Generics ? If I'm not mistaken is it related the the `any` keyword in TS ? – Raekh Void Feb 03 '20 at 09:39
  • I ment this ` – wfreude Feb 03 '20 at 09:53
  • Unfortunately I'm not skilled enough in TypeScript to answer your question. You may refer to @Bergi for that, the link he provided to you or even create a new question for that matter. – Raekh Void Feb 03 '20 at 12:22