Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
What are the Modules in Typescript ?
Next article icon

Access Modifiers in TypeScript

Last Updated : 23 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In TypeScript, access modifiers control the visibility and accessibility of class members, such as properties and methods, aligning with the principles of encapsulation and information hiding in object-oriented programming.

  • Public: Members are accessible from anywhere; this is the default modifier if none is specified.
  • Private: Members are accessible only within the class they are defined in.
  • Protected: Members are accessible within the class they are defined in and in subclasses.
JavaScript
class Animal {     public name: string;     private age: number;     protected species: string;      constructor(name: string, age: number, species: string) {         this.name = name;         this.age = age;         this.species = species;     }      public getInfo(): string {         return `${this.name} is a ${this.species}.`;     } }  class Dog extends Animal {     constructor(name: string, age: number) {         super(name, age, 'Dog');     }      public getDetails(): string {         return `${this.name} is a ${this.species} and is ${this.age} years old.`;     } }  const myDog = new Dog('Buddy', 3); console.log(myDog.name); // Accessible console.log(myDog.getInfo()); // Accessible console.log(myDog.getDetails()); // Accessible 
  • name is public: accessible from anywhere.
  • age is private: accessible only within the Animal class.
  • species is protected: accessible within Animal and its subclass Dog.

Output:

Buddy
Buddy is a Dog.
Buddy is a Dog and is 3 years old.

Types of Access Modifiers

1) Public Access Modifier

The public modifier allows class members to be accessible from anywhere. By default, all class members are public if no access modifier is specified.

JavaScript
class Animal {     public name: string;      constructor(name: string) {         this.name = name;     }      public makeSound(): void {         console.log(`${this.name} makes a sound.`);     } }  const dog = new Animal('Dog'); console.log(dog.name); // Accessible dog.makeSound(); // Accessible 
  • name and makeSound are public, allowing access from outside the class.
  • We can create an instance of Animal and access its name property and makeSound method directly.

Output:

Dog
Dog makes a sound.

2. Private Access Modifier

The private modifier restricts access to class members, making them accessible only within the class they are defined. This ensures encapsulation and protects the internal state of the object.

JavaScript
class Person {     private ssn: string;      constructor(ssn: string) {         this.ssn = ssn;     }      public getSSN(): string {         return this.ssn;     } }  const person = new Person('123-45-6789'); console.log(person.getSSN()); // console.log(person.ssn); 
  • ssn is private, preventing direct access from outside the class.
  • The public method getSSN provides controlled access to the private ssn property.

Output:

123-45-6789

3) Protected Access Modifier

The protected keyword is used to declare a class member so that it can be accessed by the class containing it and any of its subclasses, it comes handy when you want members of a class accessed in descendant classes but not outside.


JavaScript
class User {     protected age: number;      constructor(age: number) {         this.age = age;     } }  class Employee extends User {     public getRetirementAge(): number {         return this.age + 65;     } }  const employee = new Employee(30); console.log(employee.getRetirementAge()); //console.log(employee.age);  
  • age is protected, allowing access within User and its subclass Employee.
  • Attempting to access age directly from an instance of Employee results in an error.

Output:

95

Best Practice of Using Access Modifiers in TypeScript

  • Explicitly Define Access Modifiers: Always specify public, private, or protected for class members to enhance code clarity and maintainability.
  • Encapsulate Class Members: Use private or protected to restrict access to class properties and methods, ensuring internal implementation details are hidden.
  • Start with the Least Visible Modifier: Begin with private for class members and increase visibility only as necessary to maintain encapsulation.

Next Article
What are the Modules in Typescript ?
author
pankajbind
Improve
Article Tags :
  • Web Technologies
  • TypeScript
  • TypeScript-Questions

Similar Reads

  • TypeScript Accessor
    TypeScript accessors, through get and set methods, offer controlled access to object properties, enhancing encapsulation, validation, and custom logic. By using accessors, you can manage how properties are accessed and modified, supporting a more robust object-oriented design in your classes. Getter
    3 min read
  • TypeScript Indexed Access Types
    TypeScript's Indexed Access Types allow you to access the type of a specific property within an object or array using bracket notation (Type[Key]). This feature provides precise type information about properties or elements, enhancing type safety when accessing deeply nested structures or specific o
    3 min read
  • TypeScript - Access Modifiers and Readonly Properties
    In TypeScript, access modifiers and readonly properties help define how class members (properties and methods) can be accessed and modified. Access modifiers control the visibility of a class member, determining where it can be accessed from. Readonly properties, on the other hand, ensure that a var
    6 min read
  • What are the Modules in Typescript ?
    Modules in TypeScript allow you to organize code into reusable, manageable, and logical units by encapsulating functionalities into separate files. They help avoid global namespace pollution by providing scoped declarations.Modules can be imported and exported, enabling code reuse and better maintai
    4 min read
  • Higher-Order Types in TypeScript
    Higher-order types are among the advanced aspects of Typescript that give priority to types as first-class citizens, similar to higher-order functions of JavaScript that accept a function as an argument or return a function, higher-order types can accept types or return types. These are the followin
    6 min read
  • Data types in TypeScript
    In TypeScript, a data type defines the kind of values a variable can hold, ensuring type safety and enhancing code clarity. Primitive Types: Basic types like number, string, boolean, null, undefined, and symbol.Object Types: Complex structures including arrays, classes, interfaces, and functions.Pri
    3 min read
  • Interfaces in TypeScript
    TypeScript is a statically typed superset of JavaScript that adds optional types, classes, interfaces, and other features to help developers build robust and maintainable applications. One of the most powerful features of TypeScript is interfaces, which allow you to define the structure of objects,
    4 min read
  • How to Access TypeScript Private Members ?
    In this TypeScript article, we will learn how to access the TypeScript private members using different approaches. We can interact with the encapsulated components within the class and access them in the application. There are three different approaches through which we can access TypeScript private
    3 min read
  • Optional Property Class in TypeScript
    TypeScript is an Object Oriented Programming language that allows you to create classes with optional properties which may or may not be assigned with a value. We will discuss two different ways of creating optional property classes in TypeScript: Table of Content By using the Question Mark(?)By ass
    4 min read
  • How to declare a module in TypeScript ?
    A module is a piece of code that can be called or used in another code. There is nothing new about modules in Typescript. The concept of the module was introduced by JavaScript with ECMAScript 2015 release. Typescript is just re-using this feature. Will the code not work without Modules? Of course,
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences