I have a base class implementing a bunch of methods, each returning a new reference to a copy of object to allow chaining.
class Base {
constructor(public name: string) {}
funcA(): Base { return new Base('FUNC_A') }
funcB(): Base { return new Base('FUNC_B') }
}
Additionally, I have a derived class, exposing only some of the methods of the base class, and also exposing its own methods. All of these methods should return a reference to the derived class object to allow for chaining.
class Derived extends Base {
constructor() { super('DERIVED') }
funcA(): Derived { return super.funcA() }
newFunc(): Derived { return new Derived() }
}
I run into a problem in this case. The object returned by the overridden method is still an instance of the base class, whether it's casted as the derived class or not, and none of the methods defined for the first time in the derived class are defined.
One workaround comes to my mind, which is not elegant. Instead of inheritance, I could use composition to contain an instance of base class object inside a derived class object. However, for this, I need an additional constructor to accept a base class object which should be accessible outside the class, and use it like funcA(): Derived { return new Derived(this.baseObject) }
.
Is there a more elegant way of solving this problem?