YouTip LogoYouTip

Ts Access Modifiers

TypeScript Access Modifiers |

\\n\\n

Access Modifiers are one of the core features of TypeScript’s object-oriented programming.

\\n\\n

They are used to control the visibility of class members (properties, methods, constructors).

\\n\\n

Through access modifiers, encapsulation can be achieved, protecting the internal implementation details of a class.

\\n\\n
\\n\\n
\\n\\n

Why Access Modifiers Are Needed

\\n\\n

One of the three fundamental principles of object-oriented programming is encapsulation.

\\n\\n

Encapsulation means hiding data and the methods that operate on that data, exposing only necessary interfaces to the outside.

\\n\\n

Access modifiers are the means to achieve encapsulation, controlling the scope in which class members can be accessed.

\\n\\n
\\n

Concept Explanation: Access modifiers determine where class members can be accessed. TypeScript provides three access modifiers: public, protected, and private.

\\n
\\n\\n
\\n\\n

public Modifier

\\n\\n

public is the default access modifier, indicating that the member can be accessed from anywhere.

\\n\\n

Whether inside the class, in subclasses, or outside the class, public members can be accessed.

\\n\\n

Example

\\n\\n
// Define the Animal class\\n\\nclass Animal {\\n\\n  // Use public modifier for name property (can be omitted, default is public)\\n\\n  public name: string;\\n\\n  // Constructor\\n\\n  public constructor(name: string){\\n\\n    this.name= name;\\n\\n  }\\n\\n  // Public speak method\\n\\n  public speak():void{\\n\\n    console.log(this.name+" make a sound");\\n\\n  }\\n\\n}\\n\\n// Create an instance\\n\\nvar animal =new Animal("Animal");\\n\\n// Access public property from outside the class\\n\\nconsole.log(animal.name);\\n\\n// Call public method from outside the class\\n\\nanimal.speak();\\n
\\n\\n

Output:

\\n\\n
Animal Animal make a sound\\n
\\n\\n
\\n

Note: If no access modifier is specified, TypeScript defaults to public. Thus, public can be omitted, but for code clarity, it is recommended to declare it explicitly.

\\n
\\n\\n
\\n\\n

private Modifier

\\n\\n

private indicates a private member, accessible only within the class where it is defined.

\\n\\n

Neither subclasses nor external code can access private members.

\\n\\n

This is commonly used to hide internal implementation details and protect data from unintended modification.

\\n\\n

Example

\\n\\n
// Define the BankAccount class\\n\\nclass BankAccount {\\n\\n  // Use private modifier for balance; accessible only within the class\\n\\n  private balance: number;\\n\\n  // Constructor\\n\\n  constructor(initialBalance: number){\\n\\n    this.balance= initialBalance;\\n\\n  }\\n\\n  // Deposit method\\n\\n  public deposit(amount: number):void{\\n\\n    if(amount >0){\\n\\n      this.balance+= amount; // Private property accessible within the class\\n\\n      console.log("Deposit successful, current balance: "+this.balance);\\n\\n    }\\n\\n  }\\n\\n  // Get balance\\n\\n  public getBalance(): number {\\n\\n    return this.balance; // Private property accessible within the class\\n\\n  }\\n\\n}\\n\\n// Create an account instance\\n\\nvar account =new BankAccount(1000);\\n\\n// Deposit\\n\\naccount.deposit(500);\\n\\n// Get balance via public method\\n\\nconsole.log("balance: "+ account.getBalance());\\n\\n// Error: Cannot directly access private property from outside the class\\n\\n// console.log(account.balance); // Compilation error!\\n
\\n\\n

Output:

\\n\\n
Deposit successful, current balance: 1500balance: 1500\\n
\\n\\n
\\n

Best Practice: Set internal state of a class as private and provide controlled access via public methodsβ€”this is the standard approach to encapsulation.

\\n
\\n\\n
\\n\\n

protected Modifier

\\n\\n

protected indicates a protected member, accessible within the defining class and its subclasses.

\\n\\n

Protected members cannot be accessed directly from outside the class.

\\n\\n

This is useful when subclasses need to inherit certain functionality from the parent class, while hiding implementation details.

\\n\\n

Example

\\n\\n
// Define the base Person class\\n\\nclass Person {\\n\\n  // Use protected modifier for name; accessible in subclasses\\n\\n  protected name: string;\\n\\n  constructor(name: string){\\n\\n    this.name= name;\\n\\n  }\\n\\n}\\n\\n// Define the Employee class, extending Person\\n\\nclass Employee extends Person {\\n\\n  // Department is private\\n\\n  private department: string;\\n\\n  constructor(name: string, department: string){\\n\\n    super(name); // Call parent constructor\\n\\n    this.department= department;\\n\\n  }\\n\\n  // Introduce method\\n\\n  public introduce(): string {\\n\\n    // Subclass can access protected member name\\n\\n    return "I am "+this.name+",in "+this.department+" work";\\n\\n  }\\n\\n}\\n\\n// Create an employee instance\\n\\nvar emp =new Employee("Alice","Technical Department");\\n\\nconsole.log(emp.introduce());\\n\\n// Error: Cannot access protected member from outside the class\\n\\n// console.log(emp.name); // Compilation error!\\n
\\n\\n

Output:

\\n\\n
I am Alice,in Technical Department work\\n
\\n\\n
\\n

Use Case: protected is commonly used for properties that subclasses need to use, but should not be exposed externally.

\\n
\\n\\n
\\n\\n

readonly Modifier

\\n\\n

readonly is used to make a property read-only.

\\n\\n

It can only be assigned during declaration or within the constructor; after that, it cannot be modified.

\\n\\n

This is useful for defining constants or identifiers.

\\n\\n

Example

\\n\\n
// Define the User class\\n\\nclass User {\\n\\n  // A readonly property can only be assigned during initialization\\n\\n  // User ID\\n\\n  readonly id: number;\\n\\n  // Username\\n\\n  readonly name: string;\\n\\n  constructor(id: number, name: string){\\n\\n    this.id= id;\\n\\n    this.name= name;\\n\\n  }\\n\\n}\\n\\n// Create a user instance\\n\\nvar user =new User(1,"Alice");\\n\\nconsole.log("User: "+ user.id+", "+ user.name);\\n\\n// Error: Cannot modify readonly properties\\n\\n// user.id = 2; // Compilation error!\\n\\n// user.name = "Bob"; // Compilation error!\\n
\\n\\n

Output:

\\n\\n
User: 1, Alice\\n
\\n\\n
\\n

Note: readonly does not conflict with private. They can be used togetherβ€”making the property both unmodifiable and inaccessible from outside.

\\n
\\n\\n
\\n\\n

Parameter Properties

\\n\\n

TypeScript provides a shorthand syntax called parameter properties.

\\n\\n

Access modifiers can be applied directly to constructor parameters, automatically creating and initializing properties.

\\n\\n

Example

\\n\\n
// Define the Point class\\n\\nclass Point {\\n\\n  // Apply modifiers directly to constructor parameters\\n\\n  // Equivalent to declaring and initializing properties simultaneously\\n\\n  constructor(\\n\\n    // public modifier: creates public property x\\n\\n    public x: number,\\n\\n    // public modifier: creates public property y\\n\\n    public y: number,\\n\\n    // private modifier: creates private property z\\n\\n    private z: number\\n\\n  ){\\n\\n    // Constructor body can be empty; properties are auto-created\\n\\n  }\\n\\n  // Compute 3D sum\\n\\n  public sum(): number {\\n\\n    // All properties accessible within the class\\n\\n    return this.x+this.y+this.z;\\n\\n  }\\n\\n}\\n\\n// Create a point instance\\n\\nvar point =new Point(1,2,3);\\n\\n// Public properties accessible from outside\\n\\nconsole.log("x: "+ point.x);\\n\\nconsole.log("y: "+ point.y);\\n\\n// Call method\\n\\nconsole.log("Sum: "+ point.sum());\\n\\n// Error: Private property inaccessible from outside\\n\\n// console.log(point.z); // Compilation error!\\n
\\n\\n

Output:

\\n\\n
x: 1 y: 2Sum: 6\\n
\\n\\n
\\n

Code Simplification: Parameter properties significantly simplify class definitions, avoiding repetitive declaration and assignment code.

\\n
\\n\\n
\\n\\n

Comparison of Access Modifiers

\\n\\n

The table below compares the accessibility scopes of the three access modifiers.

\\n\\n\\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n \\n
ModifierWithin ClassSubclassesOutside Class (Instance)
publicβœ“ Accessibleβœ“ Accessibleβœ“ Accessible
protectedβœ“ Accessibleβœ“ Accessibleβœ— Not Accessible
privateβœ“ Accessibleβœ— Not Accessibleβœ— Not Accessible
\\n\\n
\\n

Recommendation: By default, use private; use protected when subclasses need access; use public only when full exposure is required.

\\n
\\n\\n
\\n\\n

Notes

\\n\\n
    \\n
  • Default Modifier: If no modifier is specified, public is used by default.
  • \\n
  • Constructor: Constructors can also use access modifiers to control instantiation permissions.
  • \\n
  • readonly Combination: readonly can be combined with public, protected, and private.
  • \\n
  • Compilation Impact: Access modifiers are enforced only at compile time; they have no effect at runtime.
  • \\n
\\n\\n
\\n

Best Practice: Use the most restrictive access modifier possible. Expose only necessary public interfaces, and keep internal implementation private or protected.

\\n
\\n\\n
\\n\\n

Summary

\\n\\n

Access modifiers are the core tools TypeScript uses to implement encapsulation.

\\n\\n
    \\n
  • public: Publicly accessible; the default value.
  • \\n
  • private: Private; visible only within the defining class.
  • \\n
  • protected: Protected; visible within the defining class and its subclasses.
  • \\n
  • readonly: Read-only; cannot be modified after initialization.
  • \\n
  • Parameter Properties: A shorthand syntax for simplified property declaration.
  • \\n
\\n\\n
\\n

Recommendation: Develop the habit of using access modifiersβ€”it is foundational to writing high-quality TypeScript code.

\\n
← Ts DecoratorsTs Literal Types β†’