I've been doing some experiments with tests in Angular and accessing private methods.
In JavaScript, private methods do not exist, so even if something is marked as private in a TypeScript class; at the end of the day it is still accessible on an object instance.
Consider this:
2
3 private privateMethod(input: string): string {
4 return input;
5 }
6}
Now, create an instance:
And acess the private method:
For the purposes of this, sample, I'm just sending in some value to the method and using console.log() to dump the output to the console.
TypeScript will give you an error
The error says
There is a compile problem, but this code will actually run in a browser.
You can tell TypeScript to ignore that line by using the ts-ignore directive:
2console.log(foo.privateMethod('something'));
See that IntelliJ no longer shows any errors:
I have mixed feelings about this, since we're using TypeScript and if we are often circumventing it, then that may be an underlying issue with our architecture.
However, sometimes I find myself doing this sort of thing when writing tests, than runtime code.