Access Modifiers in TypeScript

Access Modifiers in TypeScript

18 Mar 2024
Intermediate
66.8K Views
4 min read
Learn via Video Course & by Doing Hands-on Labs

TypeScript Programming Course

Access Modifiers in TypeScript: An Overview

TypeScript access modifiers are keywords that affect the visibility of class members such as properties and methods. They decide who has access to these members and where they can get it. This Typescript tutorial helps with encapsulation, an essential concept of object-oriented programming that promotes modularity and code security.

Types of Access Modifiers in Typescript

There are 3 Types of Access Modifiers in Typescript:

  1. Public
  2. Private
  3. Protected

    Types of Access Modifiers in Typescript

1. Public Access Modifier in Typescript

The public access modifier allows members of a class to be accessed from anywhere in the program, both inside and outside the class. It is the default access modifier for TypeScript class members, so you don't need to explicitly declare it unless you want to emphasize accessibility.

Example of Public Access Modifier in Typescript

class Person {

public name: string; // Accessible anywhere in the program

constructor(name: string) {

this.name = name;

}

}

const myPerson = new Person("Alice");

console.log(myPerson.name); // Output: Alice

In the Person class, the name is declared public, making it available outside of the class. Using dot notation, we may get the name of a Person object (myPerson).

2. Private Access Modifier in Typescript

The private access modifier limits a class member's visibility to the class itself. It promotes encapsulation and data protection by preventing direct access from outside the class.

Example of Private Access Modifier in Typescript

class InventoryItem {

private quantity: number; // Only accessible within InventoryItem

constructor(quantity: number) {

this.quantity = quantity;

}

public decreaseQuantity(amount: number) {

if (amount <= this.quantity) {

this.quantity -= amount; // Can access private member inside method

} else {

throw new Error("Insufficient quantity");

}

}

}

InventoryItem declares quantity as private, preventing direct access from the outside. The public decreaseQuantity method can change the quantity while verifying its value (accessing quantity).

3. Protected Access Modifier in Typescript

Members can be accessed within the class and by subclasses, but not directly from outside the class hierarchy, thanks to the protected access modifier. It encourages inheritance as well as regulated access to shared functions.

Example of Protected Access Modifier in Typescript

class User {

protected age: number; // Accessible in User and subclasses

constructor(age: number) {

this.age = age;

}

}

class Employee extends User {

public getRetirementAge(): number {

return this.age + 65; // Access protected member from subclass

}

}

const newUser = new User(25);

// newUser.age is NOT accessible (protected)

const newEmployee = new Employee(30);

console.log(newEmployee.getRetirementAge()); // Output: 95

Age is protected in User, enabling access within User and its subclass Employee.Employee's getRetirementAge method calculates retirement age using age (protected).

Readonly Access Modifier in Typescript

After initialization, the readonly access modifier marks a property as immutable, enabling it to be read but not directly updated. This improves data security and makes state management easier.

Example of Readonly Access Modifier in Typescript

class User {

readonly id: string; // Can be read but not assigned to later

constructor(id: string) {

this.id = id;

}

// Only methods can modify internal state (if needed)

changeUsername(newUsername: string) {

// Simulate internal state change (avoid direct assignment)

// ...

}

}

const user = new User("abc123");

console.log(user.id); // Output: abc123

// user.id = "xyz456"; // Error: Cannot assign to 'id' because it is readonly

user.changeUsername("new_username"); // Updating state through internal logic

The id property in User is marked as readonly, which prevents direct assignment after initialization within the constructor. The changeUsername method shows how internal logic can adjust the state without modifying the id directly.
Summary
Access modifiers in TypeScript regulate member visibility, increasing encapsulation & code security. Public members are available everywhere, private members are only accessible internally, protected members extend to subclasses, and readonly members prevent direct updates. Choosing the appropriate modifier for each member guarantees that the code is organized, secure, and modular.

FAQs

Q1. What access modifiers does TypeScript support?

There are four sorts of access modifiers in Typescript: public, private, protected, and read-only.

Q2. What are the TypeScript method modifiers?

Private, protected, and public are the three access modifiers for class properties and methods in TypeScript.

Q3. What is the difference between public and private in TypeScript?

Members who have been designated as public can be accessed from anywhere within or outside of the class. Members marked as private cannot be accessible from outside the class.

Q4. What is the TypeScript default access modifier?

TypeScript provides three types of access modifiers: public, private, and protected. Members (properties and methods) of the TypeScript class are public by default, therefore you don't need to precede members with the public keyword.

Q5. What is the distinction between protected and readonly in TypeScript?

The term protected denotes that the method or property is only accessible within the class or any class that extends it, but not externally. Finally, if the value of a readonly property is altered after its first assignment in the class constructor, the TypeScript compiler will generate an error.

Take our free typescript skill challenge to evaluate your skill

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET CHALLENGE

Share Article
Batches Schedule
About Author
Amit Kumar (Software Engineer And Author)

Experienced Software Engineer with a demonstrated history of working in the professional training & coaching industry. Skilled in Asp.net MVC, Angular, Language Integrated Query (LINQ), SQL, C++, and HTML. Strong engineering professional graduated from Sathyabama University.
Accept cookies & close this