The reason for this behavior is that the visibility of private members is limited to the type rather than the instance itself.
If private fields were allowed to be missing, it would pose a significant issue rather than just a minor problem related to correctness. Take a look at the following example:
class Identity {
private id: string = "secret agent";
public sameAs(other: Identity) {
return this.id.toLowerCase() === other.id.toLowerCase();
}
}
class MockIdentity implements Identity {
public sameAs(other: Identity) { return false; }
}
MockIdentity
serves as a version of Identity that is compatible with public access, but using it in place of the real Identity
can lead to errors when a non-mocked object interacts with a mocked one.
// Real class
class Foo {
public writeToFile(){
fileWriter.writeToFile('');
}
}
// Mock
class MockFoo implements Foo {
public writeToFile(){
// do nothing
}
}