In TypeScript, which access modifier makes members accessible only within their declaring class?

Understanding Private Access Modifier in TypeScript

In TypeScript, the private access modifier makes members accessible only within the class they were declared. This means that you can't access a private member from outside its class or from subclasses. This principle is crucial in the concept of encapsulation in object-oriented programming, where the internal state of an object is hidden from the outside world and can only be changed through the object's methods.

An example of a private member in a TypeScript class could look like this:

class MyClass {
  private myMember: string;

  constructor(myMember: string) {
    this.myMember = myMember;
  }

  displayMember() {
    console.log(this.myMember);
  }
}

let obj = new MyClass("Hello, world!");
obj.displayMember(); // Outputs: "Hello, world!"
console.log(obj.myMember); // Error: Property 'myMember' is private and only accessible within class 'MyClass'.

In this example, myMember is a private member of MyClass. Even though we initialized it through the constructor and we can display it with the method displayMember(), we cannot directly access it from the outside, as demonstrated by the attempted console.log(obj.myMember);.

It's worth noting that while the public and protected access modifiers also exist in TypeScript, they permit wider access to class members. The public modifier allows unrestricted access, while protected allows access from subclasses in addition to the class in which they're declared.

Lastly, it's important to note that TypeScript is a superset of JavaScript, which does not natively support private members. TypeScript access modifiers are therefore not enforced at runtime after the code is transpiled to JavaScript. However, they are extremely useful during development for better structuring code and catching potential problems.

Do you find this helpful?