I'm currently facing a challenge with an abstract class in typescript that includes a method to provide a callback for later use. The issue lies in the return type of the method, as it is set to the class itself, preventing me from using fluent style coding when extending the class. Specifically, I am working on extending the class and struggling to figure out how to make the method return the derived class type:
export abstract class Wizard {
...
public onPageChanging(handler: PageChangingHandler): Wizard { // Returns Wizard (but I would like this to be the derived class instead)
this.onPageChangingHandler = handler;
return this;
}
public onPageChanged(handler: PageChangedHandler): Wizard { // Returns Wizard (but I would like this to be the derived class instead)
this.onPageChangedHandler = handler;
return this;
}
...
}
export class StepWizard extends Wizard {
...
}
Snippet of the calling code:
export class Foo {
private wizard: StepWizard;
...
wireUpWizard() {
this.wizard = new StepWizard({
elem: HTMLElement,
}).onPageChanging(pc => {
// Handle Page Changing
}).onPageChanged(pc => {
// Handler Page Changed
});
// Problem arises due to inability to use fluent chaining, since onPageChanging/onPageChanged returns Wizard instead of StepWizard
}
...
}
I understand that I need to utilize Generics somehow in order to return a Generic type from onPageChanging and onPageChanged methods, but I have yet to find a solution.
Any assistance would be greatly appreciated.