Matthew Lang avatar

Table of Contents


Private methods in a class

In TypeScript, you can add private methods to a class using the private access modifier. A private method can only be accessed from within the class in which it is defined. Here’s an example:

class MyClass {
  // Public method
  public greet(): void {
    console.log("Hello, world!");
    this.sayHello(); // Calling the private method within the class
  }

  // Private method
  private sayHello(): void {
    console.log("This is a private method.");
  }
}

const instance = new MyClass();
instance.greet(); // Works fine

// instance.sayHello(); // Error: Property 'sayHello' is private and only accessible within class 'MyClass'.