If you really need the exact same code to run in every child class upon construction, then that common code probably belongs in the parent constructor. But maybe you need some child-specific code to run before the common code, in which case you still have an issue.
Either way, one possible solution would be not to override the constructor in the child classes at all, but instead let them inherit the parent constructor, which contains any common code as well as pre- and post- hooks you can override in child classes as necessary. For example:
class Parent {
// do not override the constructor, conceptually "final"
constructor() {
this.beforeCommonConstructorCode();
// add any common constructor code here
console.log("Common constructor code")
this.afterCommonConstructorCode();
}
// override this in child classes as needed
public beforeCommonConstructorCode() {
// empty
}
// override this in child classes as needed
public afterCommonConstructorCode() {
// empty
}
}
new Parent();
// in console:
// >> Common constructor code
And when you subclass Parent
, you leave the constructor alone and add code to the appropriate methods:
class Child extends Parent {
// remember, do not override constructor
public beforeCommonConstructorCode() {
console.log("Child pre-constructor code")
}
public afterCommonConstructorCode() {
console.log("Child post-constructor code")
}
}
new Child();
// in console:
// >> Child pre-constructor code
// >> Common constructor code
// >> Child post-constructor code
Note that TypeScript will not prevent child classes from overriding the constructor (there is no "final
" keyword or functionality) so discipline is needed. Otherwise, I think this behaves the way you like; you are freed from having to place common code in each subclass.
Hope that helps. Good luck.