TypeScript Access Modifiers |
\\n\\nAccess Modifiers are one of the core features of TypeScriptβs object-oriented programming.
\\n\\nThey are used to control the visibility of class members (properties, methods, constructors).
\\n\\nThrough 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\\nOne of the three fundamental principles of object-oriented programming is encapsulation.
\\n\\nEncapsulation means hiding data and the methods that operate on that data, exposing only necessary interfaces to the outside.
\\n\\nAccess modifiers are the means to achieve encapsulation, controlling the scope in which class members can be accessed.
\\n\\n\\n\\n\\nConcept Explanation: Access modifiers determine where class members can be accessed. TypeScript provides three access modifiers:
\\npublic,protected, andprivate.
\\n\\n
public Modifier
\\n\\npublic is the default access modifier, indicating that the member can be accessed from anywhere.
Whether inside the class, in subclasses, or outside the class, public members can be accessed.
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\\nOutput:
\\n\\nAnimal Animal make a sound\\n\\n\\n\\n\\n\\nNote: If no access modifier is specified, TypeScript defaults to
\\npublic. Thus,publiccan be omitted, but for code clarity, it is recommended to declare it explicitly.
\\n\\n
private Modifier
\\n\\nprivate indicates a private member, accessible only within the class where it is defined.
Neither subclasses nor external code can access private members.
This is commonly used to hide internal implementation details and protect data from unintended modification.
\\n\\nExample
\\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\\nOutput:
\\n\\nDeposit successful, current balance: 1500balance: 1500\\n\\n\\n\\n\\n\\nBest Practice: Set internal state of a class as
\\nprivateand provide controlled access viapublicmethodsβthis is the standard approach to encapsulation.
\\n\\n
protected Modifier
\\n\\nprotected indicates a protected member, accessible within the defining class and its subclasses.
Protected members cannot be accessed directly from outside the class.
\\n\\nThis is useful when subclasses need to inherit certain functionality from the parent class, while hiding implementation details.
\\n\\nExample
\\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\\nOutput:
\\n\\nI am AliceοΌin Technical Department work\\n\\n\\n\\n\\n\\nUse Case:
\\nprotectedis commonly used for properties that subclasses need to use, but should not be exposed externally.
\\n\\n
readonly Modifier
\\n\\nreadonly is used to make a property read-only.
It can only be assigned during declaration or within the constructor; after that, it cannot be modified.
\\n\\nThis is useful for defining constants or identifiers.
\\n\\nExample
\\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\\nOutput:
\\n\\nUser: 1, Alice\\n\\n\\n\\n\\n\\nNote:
\\nreadonlydoes not conflict withprivate. They can be used togetherβmaking the property both unmodifiable and inaccessible from outside.
\\n\\n
Parameter Properties
\\n\\nTypeScript provides a shorthand syntax called parameter properties.
\\n\\nAccess modifiers can be applied directly to constructor parameters, automatically creating and initializing properties.
\\n\\nExample
\\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\\nOutput:
\\n\\nx: 1 y: 2Sum: 6\\n\\n\\n\\n\\n\\nCode Simplification: Parameter properties significantly simplify class definitions, avoiding repetitive declaration and assignment code.
\\n
\\n\\n
Comparison of Access Modifiers
\\n\\nThe table below compares the accessibility scopes of the three access modifiers.
\\n\\n| Modifier | \\nWithin Class | \\nSubclasses | \\nOutside Class (Instance) | \\n
|---|---|---|---|
public | \\n β Accessible | \\nβ Accessible | \\nβ Accessible | \\n
protected | \\n β Accessible | \\nβ Accessible | \\nβ Not Accessible | \\n
private | \\n β Accessible | \\nβ Not Accessible | \\nβ Not Accessible | \\n
\\n\\n\\nRecommendation: By default, use
\\nprivate; useprotectedwhen subclasses need access; usepubliconly when full exposure is required.
\\n\\n
Notes
\\n\\n- \\n
- Default Modifier: If no modifier is specified,
publicis used by default. \\n - Constructor: Constructors can also use access modifiers to control instantiation permissions. \\n
- readonly Combination:
readonlycan be combined withpublic,protected, andprivate. \\n - Compilation Impact: Access modifiers are enforced only at compile time; they have no effect at runtime. \\n
\\n\\n\\nBest Practice: Use the most restrictive access modifier possible. Expose only necessary public interfaces, and keep internal implementation
\\nprivateorprotected.
\\n\\n
Summary
\\n\\nAccess 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
\\nRecommendation: Develop the habit of using access modifiersβit is foundational to writing high-quality TypeScript code.
\\n
YouTip