What if your secret data was accidentally shared with everyone? Access modifiers stop that from happening!
Why Access modifiers public private protected in Typescript? - Purpose & Use Cases
Imagine you are building a big app with many parts, and you want to keep some information safe inside each part. Without clear rules, anyone can change anything anywhere, like leaving your diary open for everyone to read and write.
Manually checking who can see or change each piece of data is slow and confusing. Mistakes happen easily, causing bugs or security problems, like accidentally sharing your password with strangers.
Access modifiers like public, private, and protected act like clear signs on doors: public means anyone can enter, private means only the owner can enter, and protected means only close friends can enter. This keeps your code safe and organized.
class User { name: string; password: string; } // Anyone can access and change password directly
class User { public name: string; private password: string; } // password is hidden and safe inside the class
It lets you protect important data and control who can use or change it, making your programs safer and easier to manage.
Think of a bank account: your balance is private so only the bank can change it, but your name is public so anyone can see it on your card.
Access modifiers control visibility and access to class members.
They prevent accidental or harmful changes to important data.
Using them makes your code more secure and easier to understand.
Practice
Solution
Step 1: Understand access modifiers
publicmeans anyone can access the member,privaterestricts access to the class only, andprotectedallows access to the class and its subclasses.Step 2: Identify the modifier allowing access from anywhere
Onlypublicallows access from outside the class, including other classes and code.Final Answer:
public -> Option BQuick Check:
public = accessible everywhere [OK]
- Confusing private with public access
- Thinking protected is accessible outside class
- Assuming readonly controls access
age in a TypeScript class?Solution
Step 1: Recall TypeScript property declaration syntax
Access modifiers come before the property name and type, e.g.,private age: number;.Step 2: Identify correct modifier placement
private age: number;correctly placesprivatebefore the property name and type.age: private number;has incorrect order.Final Answer:
private age: number; -> Option AQuick Check:
Modifier before name and type [OK]
- Placing modifier after property name
- Using invalid syntax like 'age: private number;'
- Confusing protected and private keywords
class Animal {
protected sound = 'Roar';
}
class Lion extends Animal {
public makeSound() {
return this.sound;
}
}
const lion = new Lion();
console.log(lion.makeSound());Solution
Step 1: Understand protected access
The propertysoundisprotected, so it can be accessed inside the class and its subclasses likeLion.Step 2: Trace method call and output
ThemakeSoundmethod returnsthis.sound, which is "Roar". So,console.logprints "Roar".Final Answer:
"Roar" -> Option CQuick Check:
Protected allows subclass access [OK]
- Thinking protected is inaccessible outside class
- Confusing private with protected
- Expecting runtime error for protected access
class Person {
private name: string = 'Alice';
}
const p = new Person();
console.log(p.name);Solution
Step 1: Check access modifier usage
The propertynameis declaredprivate, so it cannot be accessed outside the classPerson.Step 2: Analyze the console.log statement
Trying to accessp.nameoutside the class causes a compile-time error about private access.Final Answer:
Error: Cannot access private property 'name' outside class -> Option DQuick Check:
Private blocks outside access [OK]
- Assuming private properties are accessible outside
- Confusing private with protected
- Expecting code to print property value
class Vehicle {
protected speed: number = 0;
private engineOn: boolean = false;
public start() {
this.engineOn = true;
}
}
class Car extends Vehicle {
public accelerate() {
this.speed += 10; // Line 1
this.engineOn = true; // Line 2
}
}
const car = new Car();
car.accelerate();Solution
Step 1: Understand access levels of properties
speedisprotected, so accessible in subclassCar.engineOnisprivate, accessible only insideVehicle.Step 2: Analyze lines in subclass method
Line 1 accessesspeedand is valid. Line 2 tries to accessengineOndirectly, which causes a compilation error.Final Answer:
Line 2: Accessing private property 'engineOn' in subclass -> Option AQuick Check:
Private blocks subclass access [OK]
- Assuming private is accessible in subclasses
- Thinking protected is private
- Ignoring error on private property access
Ready to prove it?
Pass the test and this pattern moves unknown
