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 if you try to do so at runtime.

Consider this:

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

Now, create an instance:

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

And access 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.

Instead of Object.property notation, I'm using object array notation to drill into the method.

TSLint is giving me an error

The error says:

view plain print about
1TSLint: object access via string literals is disallowed(no-string-literal)

This code will run in a browser without issues.

I could go change the linting rules universally in the app, or I could tell the app to ignore this one line. For the purposes of this post, I want to do the latter.

You can tell TSLint to ignore that line by using the tslint:disable-next-line directive:

view plain print about
1// tslint:disable-next-line

See that IntelliJ no longer shows any errors:

Primarily, this is only something I'd use within tests when I want to access a private method directly. We could argue about whether that is a good idea or not all day but I often decide to do so when writing unit tests.