Introduction to Access Modifiers
Access modifiers in TypeScript control where class properties and methods can be accessed. They help developers define a clear boundary between the functionality a class exposes and the implementation details it keeps internal.
Consider a BankAccount class. Other parts of an application may need to check the current balance or deposit money, but they should not be able to change the balance directly and bypass the account's business rules. Access modifiers help establish these restrictions.
TypeScript supports three primary access modifiers: public, private, and protected. It also supports readonly, which restricts property reassignment, and allows modifiers to be used with constructor parameter properties.
Understanding these features helps you design classes with predictable behavior, well-defined interfaces, and fewer accidental modifications. It is also important to understand which restrictions are enforced by TypeScript's type checker and which provide privacy at runtime.
1. Understanding public Access Modifier
The public modifier makes a class member accessible wherever the class instance or class itself is available. It is the default visibility for ordinary class members in TypeScript, so you generally do not need to write it explicitly.
class User {
public name: string;
constructor(name: string) {
this.name = name;
}
public displayName(): void {
console.log(this.name);
}
}
const user = new User("Abhinash");
console.log(user.name);
user.displayName();
Both the name property and displayName method are public. Code outside the class can read the property and call the method.
The same class can be written without explicitly declaring public:
class User {
name: string;
constructor(name: string) {
this.name = name;
}
displayName(): void {
console.log(this.name);
}
}
The two versions have the same visibility behavior. Use public explicitly when it improves readability, documents the class's intended interface, or makes a comparison with other modifiers clearer.
Public members are appropriate for operations and values that external code is expected to use. Avoid exposing mutable properties unnecessarily when changing them could violate the class's rules.
2. Understanding private Access Modifier
The private modifier restricts access to a class member from outside the declaring class under TypeScript's type-checking rules. It is useful for implementation details that should only be manipulated by the class itself.
class BankAccount {
private balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
public getBalance(): number {
return this.balance;
}
public deposit(amount: number): void {
if (amount > 0) {
this.balance += amount;
}
}
}
const account = new BankAccount(1000);
console.log(account.getBalance());
account.deposit(500);
// Compilation error:
// console.log(account.balance);
// Compilation error:
// account.balance = -100;
The balance property is private, so TypeScript prevents ordinary external code from accessing it directly. Instead, callers interact with the public getBalance and deposit methods.
This design allows the class to control how its internal state changes. For example, the deposit method rejects non-positive amounts rather than allowing arbitrary modifications to the balance.
TypeScript's traditional private modifier is primarily enforced by the type checker. It does not automatically provide hard runtime privacy in emitted JavaScript. If runtime-enforced private fields are required, JavaScript's #field syntax is a separate option.
3. Understanding protected Access Modifier
The protected modifier allows a member to be accessed inside its declaring class and its subclasses. Unlike public members, protected members are not accessible through an ordinary external instance reference.
class Employee {
constructor(
public name: string,
protected department: string
) {}
public getDepartment(): string {
return this.department;
}
}
class Developer extends Employee {
public describeRole(): string {
return this.name + " works in " + this.department;
}
}
const developer = new Developer(
"Abhinash",
"Engineering"
);
console.log(developer.describeRole());
console.log(developer.getDepartment());
// Compilation error:
// console.log(developer.department);
The Developer class inherits the protected department property from Employee and can use it within its own methods. External code can still use the public methods and properties exposed by the class.
Protected is useful when a base class needs to share certain implementation details with related subclasses without exposing those details as part of the public API.
Be careful when making many properties protected. Subclasses become dependent on the base class's internal structure, which can make future changes harder. Prefer public methods when subclasses only need a specific operation rather than direct access to internal state.
4. Comparing public, private, and protected
These three modifiers differ mainly in which parts of the program can access a member through TypeScript's type system.
| Modifier | Declaring class | Subclass | External code |
|---|---|---|---|
public |
Yes | Yes | Yes |
protected |
Yes | Yes | No |
private |
Yes | No | No |
These rules describe ordinary access through TypeScript's type system. Traditional TypeScript private and protected members do not provide the same runtime guarantees as JavaScript private fields.
A practical approach is to make members public when callers genuinely need them, private when they belong only to the class's implementation, and protected when subclasses need access to a member as part of an intentional inheritance design.
5. Using readonly with Class Properties
The readonly modifier prevents a property from being reassigned through a reference typed with that readonly declaration. A readonly property can be initialized in its declaration or, when declared directly on the class, in the declaring class's constructor.
class Product {
readonly id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
rename(newName: string): void {
this.name = newName;
}
}
const product = new Product(101, "Keyboard");
product.rename("Mechanical Keyboard");
// Compilation error:
// product.id = 202;
The id property is assigned when the product is initialized and cannot be reassigned through ordinary TypeScript code afterward. The name property remains mutable and can be updated by the rename method.
You can combine readonly with visibility modifiers:
class Account {
public readonly accountId: string;
private balance: number;
constructor(accountId: string, initialBalance: number) {
this.accountId = accountId;
this.balance = initialBalance;
}
getBalance(): number {
return this.balance;
}
}
This combination makes the account identifier publicly readable but prevents its reassignment through ordinary TypeScript code. The balance remains private and is exposed through a controlled method.
Readonly is a compile-time restriction, not an automatic runtime freezing mechanism. It also does not recursively make nested object properties readonly.
6. Using Access Modifiers in Constructor Parameters
TypeScript supports parameter properties, which allow constructor parameters to declare and initialize class properties directly. Adding public, private, protected, or readonly to a constructor parameter enables this shorthand.
class User {
constructor(
public name: string,
private passwordHash: string,
protected role: string,
public readonly id: number
) {}
public verifyPasswordHash(candidate: string): boolean {
return this.passwordHash === candidate;
}
}
const user = new User(
"Abhinash",
"hash-value",
"admin",
101
);
console.log(user.name);
console.log(user.id);
console.log(user.verifyPasswordHash("hash-value"));
// Compilation error:
// console.log(user.passwordHash);
// Compilation error:
// console.log(user.role);
// Compilation error:
// user.id = 202;
Each constructor parameter becomes an initialized property with the specified visibility or reassignment restriction. The name property is public, passwordHash is private, role is protected, and id is public and readonly.
Parameter properties help reduce repetitive property declarations and constructor assignments. They are particularly useful when a class primarily stores the values provided during construction.
In production authentication systems, do not use a simple string equality check as a complete password verification strategy. Password handling requires appropriate password hashing and verification mechanisms; the example only demonstrates member visibility.
7. Understanding JavaScript Private Fields with #
JavaScript supports private class fields that begin with the # character. TypeScript supports this syntax as well. Unlike the traditional TypeScript private modifier, these fields have runtime-enforced privacy.
class BankAccount {
#balance: number;
constructor(initialBalance: number) {
this.#balance = initialBalance;
}
deposit(amount: number): void {
if (amount > 0) {
this.#balance += amount;
}
}
getBalance(): number {
return this.#balance;
}
}
const account = new BankAccount(1000);
account.deposit(500);
console.log(account.getBalance());
// Invalid JavaScript:
// account.#balance;
The #balance field is private at runtime. JavaScript prevents code outside the class from accessing it directly, rather than relying only on TypeScript's compile-time checks.
These fields use a distinct JavaScript syntax and cannot be accessed with ordinary bracket notation such as account["#balance"]. That expression refers to a different property name rather than the private field.
Choose traditional private when TypeScript-level restrictions are sufficient, especially when working with existing class patterns. Choose JavaScript private fields when runtime privacy is part of the requirement and the project's supported JavaScript target and runtime allow them.
8. Access Modifiers and Inheritance
Access modifiers influence how a derived class can use inherited members. Public and protected members can be available to subclasses, while private members declared using the traditional TypeScript private modifier cannot be accessed by subclasses through normal TypeScript member access.
class Employee {
public name: string;
protected department: string;
private salary: number;
constructor(
name: string,
department: string,
salary: number
) {
this.name = name;
this.department = department;
this.salary = salary;
}
protected getSalary(): number {
return this.salary;
}
}
class Developer extends Employee {
constructor(name: string, salary: number) {
super(name, "Engineering", salary);
}
describe(): string {
const salary = this.getSalary();
return this.name +
" works in " +
this.department +
" and earns " +
salary;
}
}
const developer = new Developer("Abhinash", 60000);
console.log(developer.describe());
// Compilation error:
// developer.department;
// Compilation error:
// developer.getSalary();
Developer can access the inherited public name property and protected department property inside its own methods. It can also call the protected getSalary method from within the subclass.
External code cannot access department or getSalary directly through the developer instance. The private salary field is restricted to the Employee class's implementation, while the protected method provides a controlled path for subclasses to use the value.
Inheritance should expose only the members that subclasses genuinely need. A narrow protected API can make a base class easier to evolve without forcing all subclasses to depend on every internal detail.
9. Controlling Access with Getters and Setters
Sometimes a property should be readable from outside the class but writable only through validation logic. TypeScript getters and setters allow a class to expose property-like syntax while controlling how its value is read or changed.
class Product {
private currentPrice: number;
constructor(initialPrice: number) {
this.currentPrice = initialPrice;
}
get price(): number {
return this.currentPrice;
}
set price(value: number) {
if (!Number.isFinite(value) || value < 0) {
throw new Error("Price must be a non-negative number");
}
this.currentPrice = value;
}
}
const product = new Product(499);
console.log(product.price);
product.price = 599;
console.log(product.price);
// Throws an error at runtime:
// product.price = -100;
The currentPrice property is private. Outside code reads the value through the getter and updates it through the setter, which checks the proposed value before changing the internal state.
This design is useful when property updates must follow business rules. A getter can expose a read-only view, while a setter can validate or normalize the new value.
A private property alone restricts external access, but it does not automatically validate values. Getters and setters add behavior when controlled reading or writing is actually required.
10. Common Mistakes to Avoid
- Making everything public: exposing every property can allow callers to bypass class rules. Keep the public API focused on operations and values external code genuinely needs.
- Confusing private with protected: private members are restricted to their declaring class under TypeScript's access rules, while protected members can also be used by subclasses.
- Treating TypeScript private as runtime privacy: traditional private is enforced by the compiler. Use JavaScript #private fields when runtime-enforced privacy is required.
- Assuming readonly validates values: readonly prevents reassignment through the type system; it does not check whether the initial value satisfies business rules.
- Overusing protected members: too many protected properties and methods can tightly couple subclasses to the base class's implementation.
- Exposing sensitive data through public methods: making a field private does not help if a public method exposes information that should remain confidential.
- Using access modifiers as authorization: class visibility does not replace authentication, authorization, API validation, or other security controls.
- Using getters and setters without a reason: add them when controlled access, validation, or computed behavior is required rather than introducing unnecessary complexity.
11. Best Practices for Access Modifiers
- Expose a small, clear public interface and keep implementation details private when possible.
- Use protected only when subclasses need access to specific members as part of an intentional inheritance design.
- Use readonly for values that should not be reassigned after initialization through ordinary TypeScript code.
- Use parameter properties when they make constructor initialization more readable.
- Choose JavaScript #private fields when runtime-enforced privacy is required.
- Use getters and setters when a property needs controlled access, validation, or derived behavior.
- Keep business-rule validation separate from compile-time type restrictions where runtime checks are required.
- Do not rely on class access modifiers as security controls for API endpoints, credentials, or sensitive data.
- Review the public API of a base class carefully before exposing additional protected members to subclasses.
Conclusion
Access modifiers help define how TypeScript classes expose and protect their members. Public members form the accessible interface, private members keep implementation details within the class's type-checking boundary, and protected members support controlled access from subclasses.
Readonly properties, constructor parameter properties, JavaScript private fields, and getters and setters provide additional ways to control how object state is initialized, accessed, and modified.
By exposing only what callers need and choosing each modifier according to the intended design, you can build classes that are easier to maintain and less vulnerable to accidental state changes. Always distinguish compile-time access restrictions from runtime privacy and application-level security.