TypeScript Access Modifiers


TypeScript: Access Modifiers Explained Differently

In TypeScript, you can define visibility rules for class properties and methods. These special keywords manage how and where parts of your code can be reached or touched.


1. public – Open Gate

Everything labeled public can be used anywhere: inside the class, from outside, or by other objects.

class Car {   
   public model: string;    

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

const tesla = new Car("Model S"); 
console.log(tesla.model); // works fine 

If you skip writing a modifier, it's assumed to be public.


2. private – Behind the Curtain

Marking something private means it’s locked inside the class. No one outside can peek or modify it.

class Vault {   
   Private code: string;    
   
   constructor(code: string) {     
       this.code = code;  
    }   

    accessVault() {     
       return this.code;   
    } 
} 

 const secret = new Vault("007"); 

Useful for hiding important details.


3. protected – Family Only

The protected tag allows access only within the class and its children (derived classes). Outsiders can’t reach it.

class Creature {   
    protected power: number = 100; 
 }  

class Dragon extends Creature {   
     roar() {     
        return `Power is ${this.power}`;   
    } 
} 

 const draco = new Dragon(); // console.log(draco.power); 

It’s great when you’re building on top of another class but still want to keep things guarded.


Summary Table

Modifier Reachable From Ideal Use
public Everywhere General features
private Inside same class Hide internal logic or data
protected Class + Subclasses Inheritance with boundaries

Prefer Learning by Watching?

Watch these YouTube tutorials to understand TYPESCRIPT Tutorial visually:

What You'll Learn:
  • 📌 Access Modifiers in TypeScript
  • 📌 Typescript tutorial #27 Public and Private access modifiers
Previous Next