In this specific scenario, when the public method message()
is included and the greet()
function operates as anticipated:
class Foo {
public greet() {
console.log(`Hello, ${this.getMessage()}`);
}
getMessage(): string {
return "I am Foo";
}
}
class Goo extends Foo {
getMessage(): string {
return "I am Goo";
}
}
However, changing getMessage()
to private causes issues with the compilation of class Goo:
class Foo {
public greet() {
console.log(`Hello, ${this.getMessage()}`);
}
private getMessage(): string {
return "I am Foo";
}
}
class Goo extends Foo {
private getMessage(): string {
return "I am Goo";
}
}
Many developers use private methods to enhance code readability by breaking down complex functions into smaller, more manageable pieces. This practice is recommended in various programming resources. However, TypeScript poses a challenge when modifications are required for subclasses that depend on these private methods.
Is there an alternative approach to address this issue without duplicating public methods in extended classes or exposing internal methods through public interfaces?
Furthermore, it raises curiosity regarding the TypeScript team's rationale behind the restriction that allows overriding of public methods but not private methods.