How can I achieve something similar to this pattern in typescript?
class A {
Init(param1: number) {
// some code
}
}
class B extends A {
Init(param1: number, param2: string) {
// some more code
}
}
The code snipped above appears like it should work, however on close inspection of How Typescript function overloading works it makes sense that an error is thrown:
TS2415: 'Class 'B' incorrectly extends base class 'A'.
Types of property 'Init' are incompatible.
I know that constructor functions allow this behaviour, but I can't use constructors here as these objects are pooled for memory efficiency.
I could provide another definition of Init() in class A:
class A {
Init(param1: number, param2: string): void;
Init(param1: number) {
// some code
}
}
However this is less than ideal as now the base class needs to know about all of its derived classes.
A third option would be to rename the Init method in class B but that would not only be pretty ugly and confusing, but leave exposed the Init() method in the base class, which would cause difficult-to-detect bugs when the base class Init() is called by mistake.
Is there any way to implement this pattern that doesn't have the pitfalls of the aforementioned approaches?