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:

view plain print about
1export class ClassWithPrivateMethod {
3 private privateMethod(input: string): string {
4 return input;
5 }

Now, create an instance:

view plain print about
1const foo = new ClassWithPrivateMethod();

And acess the private method:

view plain print about

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

view plain print about
1TS2341: Property 'privateMethod' is private and only accessible within class 'ClassWithPrivateMethod'

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:

view plain print about
1// @ts-ignore

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.