In my journey of exploration, I decided to try implementing a class within another class in TypeScript.
Here is the code snippet I came up with and tested on the Playground link:
class A {
private f() { console.log("f"); }
public g() { console.log("G"); }
}
class B implements A {
public g() { console.log("g"); }
}
Upon testing, I encountered the error:
Class 'B' incorrectly implements class 'A' --- property 'f' is missing in type 'B'
. This error also suggested that I should use extends
instead of implements
.
In an attempt to rectify this, I tried introducing a private field named f
, as using public
resulted in different access modifiers, as seen in this Playground link.
However, this led to a new error:
Class 'B' incorrectly implements class 'A'. Types have separate declarations of a private property 'f'
, which left me baffled.
- Why is the presence of private members crucial in this context? Does it mean that if I use different data structures to implement the same algorithm, I would have to declare similarly named private properties to satisfy type checking?
- Why does the error persist even when
f
is implemented as a private function?
Although I would not typically approach tasks this way, I am intrigued by the workings of TypeScript in this scenario.
Thank you for any insights!