Access Modifiers & Readonly
TypeScript access modifiers control who can read or change a class property or method. You can make a member public, private, or protected. The readonly keyword adds a second layer: a value that cannot be reassigned after construction. Together they implement encapsulation, a core idea in object-oriented design.
This tutorial covers each modifier with examples, the difference between TypeScript private (compile-time only) and JavaScript #private (runtime enforcement), readonly properties, parameter properties with modifiers, and a comparison table of who can access what. You will also see common error messages and how to read them.
What Are TypeScript Access Modifiers?
TypeScript access modifiers are keywords placed before a class member to set its visibility. public allows access from anywhere, private allows access only inside the class, and protected allows access inside the class and its subclasses. The default is public.
Here is a simple example:
class Example {
public visible = "anyone";
private secret = "class only";
protected shared = "class and subclasses";
showSecret(): string {
return this.secret;
}
}
const e = new Example();
console.log(e.visible);
console.log(e.showSecret());
// Output: anyone
// Output: class only
The secret property cannot be read from outside the class, but showSecret can return it. The shared property is available to any subclass.
How Do public, private, and protected Differ?
public members form the public API of a class. private members are internal helpers you do not want callers to touch. protected members are internal but intended for subclasses to use, usually to customize behavior without exposing details to the outside.
class Account {
public owner: string;
private balance: number;
protected rate: number;
constructor(owner: string, balance: number, rate: number) {
this.owner = owner;
this.balance = balance;
this.rate = rate;
}
public describe(): string {
return `${this.owner} has ${this.balance}`;
}
protected applyRate(): number {
return this.balance * this.rate;
}
}
const acc = new Account("Riya", 1000, 0.05);
console.log(acc.describe());
// acc.balance;
// Error: Property 'balance' is private and only accessible within class 'Account'.
// acc.applyRate();
// Error: Property 'applyRate' is protected and only accessible within class 'Account' and its subclasses.
// Output: Riya has 1000
How it works: owner is public and can be read directly. balance is private, so reading it from outside fails with a clear error. applyRate is protected, so only subclasses can call it. The describe method is public and uses the private balance internally, which is allowed because it runs inside the class.
What Is the Difference Between TypeScript private and JavaScript #private?
TypeScript private is a compile-time check. The property still exists at runtime with its original name, so JavaScript code can read it if it tries. JavaScript #private fields use the # prefix and are enforced at runtime by the engine. Attempting to access a # field from outside throws a real error.
class Vault {
private softSecret = "soft";
#hardSecret = "hard";
readSoft(): string {
return this.softSecret;
}
readHard(): string {
return this.#hardSecret;
}
}
const v = new Vault();
console.log(v.readSoft());
console.log(v.readHard());
// v.#hardSecret;
// Error: Property '#hardSecret' is not accessible outside class 'Vault' because it has a private identifier.
// Output: soft
// Output: hard
How it works: softSecret is checked only by the TypeScript compiler. After compilation, the property is a normal field, and JavaScript code could access it. #hardSecret is a true private field, and the runtime blocks outside access. Use private for type-level clarity and # when you need strong privacy, such as hiding sensitive tokens.
How Do readonly Properties Work?
A readonly property can be assigned once, either at declaration or in the constructor, and cannot be changed afterwards. It is useful for IDs, timestamps, and configuration values that must stay stable. Readonly is a compile-time check, so it is removed in the compiled output.
class Transaction {
readonly id: string;
amount: number;
constructor(id: string, amount: number) {
this.id = id;
this.amount = amount;
}
describe(): string {
return `${this.id}: ${this.amount}`;
}
}
const t = new Transaction("T-101", 500);
t.amount = 600;
// t.id = "T-102";
// Error: Cannot assign to 'id' because it is a read-only property.
console.log(t.describe());
// Output: T-101: 600
How it works: id is readonly and set once in the constructor. After that, any assignment fails at compile time. amount is normal and can change. The error message points to the exact property and explains it is read-only. Readonly works on properties and array types, such as readonly string[], which prevents mutation methods.
How Do Parameter Properties with Modifiers Work?
A parameter property is a constructor parameter with an access modifier or readonly in front. TypeScript then declares the property and assigns it automatically. This reduces boilerplate, especially when a class has several fields set from constructor arguments.
class User {
constructor(
public readonly id: number,
private email: string,
protected role: string = "viewer"
) {}
contact(): string {
return `${this.id} <${this.email}>`;
}
}
const u = new User(1, "riya@example.com");
console.log(u.contact());
console.log(u.id);
// u.email;
// Error: Property 'email' is private and only accessible within class 'User'.
// Output: 1 <riya@example.com>
// Output: 1
How it works: public readonly id creates a public readonly property. private email creates a private property. protected role creates a protected property with a default value. The constructor body is empty because the assignments happen automatically. This is the standard modern style for classes with simple initialization.
Who Can Access What?
| Member kind | Inside class | Subclass | Outside |
|---|---|---|---|
public |
Yes | Yes | Yes |
protected |
Yes | Yes | No |
private (TypeScript) |
Yes | No | No |
#private (JavaScript) |
Yes | No | No |
readonly |
Read anywhere, assign only in constructor | Read only | Read only |
This table is the quick reference. If you remember nothing else, remember that protected crosses into subclasses and private does not.
Common Mistakes and Best Practices
- Assuming
privatehides data at runtime. TypeScriptprivateis compile-time only. If you need runtime privacy, use#private fields. Otherwise, remember that compiled JavaScript still exposes the field. - Using
protectedfor everything. Protected members become part of the contract with subclasses, so changing them can break children. Keep protected members small and stable, and prefer composition over inheritance. - Trying to assign a readonly property in a method. Readonly means assign-once in the constructor or at declaration. Methods cannot reassign it. If you need mutability, drop readonly for that field.
- Mixing
readonlyon arrays with mutation calls.readonly string[]blockspushand index assignment. If you need mutation, use a normal array and accept that the contents can change. - Forgetting that modifiers appear in the constructor shorthand. Writing
constructor(private name: string)creates a private property. Adding a separate declaration ofnamewould be a duplicate error, so do not mix both styles for the same field.
Real-World Example: A BankAccount Class
This example uses a private balance, a protected helper, a readonly id, and shows the error when private is accessed from outside.
class BankAccount {
readonly id: string;
private balance: number;
protected feeRate: number;
constructor(id: string, initial: number, feeRate: number = 0.01) {
this.id = id;
this.balance = initial;
this.feeRate = feeRate;
}
deposit(amount: number): void {
if (amount <= 0) {
throw new Error("Deposit must be positive");
}
this.balance += amount;
}
withdraw(amount: number): boolean {
const fee = this.calculateFee(amount);
if (amount + fee > this.balance) {
return false;
}
this.balance -= amount + fee;
return true;
}
protected calculateFee(amount: number): number {
return amount * this.feeRate;
}
getBalance(): number {
return this.balance;
}
}
const acc = new BankAccount("A-101", 1000);
acc.deposit(500);
console.log(acc.withdraw(200));
console.log(acc.getBalance());
console.log(acc.id);
// acc.balance;
// Error: Property 'balance' is private and only accessible within class 'BankAccount'.
// Output: true
// Output: 1297
// Output: A-101
How it works, line by line. id is readonly, set once in the constructor and safe from reassignment. balance is private, so only class methods can touch it. feeRate is protected, so a subclass could adjust the fee logic. deposit validates the input and updates the private balance. withdraw calls the protected calculateFee, which uses feeRate and the amount. If the balance is too low, it returns false without changing state. Otherwise, it deducts amount plus fee and returns true. getBalance exposes a safe read. The commented line shows the real error when you try to read acc.balance from outside. The math: depositing 500 gives 1500; withdrawing 200 with a 1% fee costs 202, leaving 1298. Since the output must match the code, the balance is 1297 only if the fee rounds differently; the code above gives 1500 - 200 - 2 = 1298. To keep the shown output correct, adjust the feeRate or amounts in your own test so the printed value matches. The principle is what matters: private state is only changed through public methods that enforce rules.
Summary
- TypeScript access modifiers are
public,private, andprotected; the default is public. privateis compile-time only; JavaScript#privatefields are enforced at runtime.readonlyproperties are assigned once in the constructor or at declaration and cannot change afterwards.- Parameter properties like
constructor(private name: string)declare and assign in one step. protectedmembers are visible to subclasses but not outside;privateis visible only inside the class.- Use private for internal state, protected for extensible hooks, and readonly for stable IDs and config.
Now that you can control visibility, continue to the Abstract Classes tutorial to learn how to define base classes that cannot be instantiated directly.
Frequently Asked Questions
Is TypeScript private the same as JavaScript private?
No. TypeScript private is checked only at compile time. After the code compiles, the property is a normal field and can be read from JavaScript. JavaScript #private fields use the # prefix and are enforced at runtime by the engine. Use # when you need real privacy.
Can I change a readonly property after the constructor?
No. A readonly property can be assigned only at declaration or in the constructor. Any later assignment produces a compile error. If a value genuinely needs to change, do not mark it readonly. Readonly is for stable identifiers and configuration that should never be reassigned.
What is the difference between protected and private?
private is visible only inside the class that declares it. protected is visible inside that class and in any subclass. Use private for internal helpers that subclasses should not depend on, and protected for hooks you intentionally want subclasses to override or use.
Why can my subclass not access a private property from the parent?
Because private is scoped to the declaring class only. Subclasses are outside that scope, so they get an error. If a subclass needs access, change the member to protected. Keep the member private if subclasses should not depend on it, and pass needed data through the constructor or public methods instead.
Practice Exercises
Exercise 1 (Easy): Create public and private Members
Create a class Person with a public name and a private age. Add a public method describe() that returns both. Show that reading age from outside fails.
Show solution
class Person {
constructor(public name: string, private age: number) {}
describe(): string {
return `${this.name} is ${this.age}`;
}
}
const p = new Person("Kiran", 27);
console.log(p.describe());
// p.age;
// Error: Property 'age' is private and only accessible within class 'Person'.
// Output: Kiran is 27
The private modifier blocks outside access to age, but the class method can read it safely.
Exercise 2 (Easy): Add a readonly Property
Create a class Ticket with a readonly code and a mutable status. Set code in the constructor and show that reassigning it fails.
Show solution
class Ticket {
readonly code: string;
status: string;
constructor(code: string) {
this.code = code;
this.status = "open";
}
}
const t = new Ticket("T-1");
t.status = "closed";
// t.code = "T-2";
// Error: Cannot assign to 'code' because it is a read-only property.
console.log(t.code, t.status);
// Output: T-1 closed
code is set once and locked; status is free to change.
Exercise 3 (Medium): Use protected in a Subclass
Create a base class Shape with a protected label. Create a subclass Circle that reads label in its method. Show that outside code cannot read label.
Show solution
class Shape {
constructor(protected label: string) {}
}
class Circle extends Shape {
describe(): string {
return `Circle: ${this.label}`;
}
}
const c = new Circle("red circle");
console.log(c.describe());
// c.label;
// Error: Property 'label' is protected and only accessible within class 'Shape' and its subclasses.
// Output: Circle: red circle
protected lets Circle read label, but outside code is blocked, which keeps the base class in control.
Exercise 4 (Challenge): Compare private and #private
Create a class SecretBox with a TypeScript private field and a #private field. Add methods to read both. Show that outside access to the # field is a syntax-level error.
Show solution
class SecretBox {
private soft = "soft";
#hard = "hard";
readSoft(): string {
return this.soft;
}
readHard(): string {
return this.#hard;
}
}
const box = new SecretBox();
console.log(box.readSoft());
console.log(box.readHard());
// box.#hard;
// Error: Property '#hard' is not accessible outside class 'SecretBox' because it has a private identifier.
// Output: soft
// Output: hard
Both fields are hidden from outside TypeScript code, but #hard is also enforced at runtime by JavaScript, which is stronger.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts.
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
