call a private method on an instance of a class in typescript

To call a private method on an instance of a class in TypeScript, you can use the # symbol before the method name to indicate that it is a private method. Here's an example:

index.ts
class MyClass {
  #privateMethod(): void {
    console.log("This is a private method.");
  }

  public callPrivateMethod(): void {
    this.#privateMethod();
  }
}

const myInstance = new MyClass();
myInstance.callPrivateMethod(); // This logs "This is a private method."
272 chars
13 lines

In this example, #privateMethod is a private method of MyClass. We can call this private method within the class using this.#privateMethod(). Notice that when we try to call #privateMethod outside of the class, we get a TypeError saying that the method is private.

Keep in mind that private methods are a new feature in TypeScript 3.8 and above, so make sure you're using a compatible version of TypeScript.

gistlibby LogSnag