TypeScript Classes
🏛️ TypeScript Classes
They support Object-Oriented Programming (OOP) concepts like encapsulation, inheritance, and polymorphism, with strong typing.
1️⃣ Basic Class
2️⃣ Access Modifiers
TypeScript provides three access modifiers:
| Modifier | Access |
|---|---|
public |
Accessible everywhere (default) |
private |
Accessible only inside the class |
protected |
Accessible inside class & subclasses |
❌ user.password → Error
3️⃣ Parameter Properties (Shortcut ⭐)
TypeScript allows defining and initializing properties directly in constructor.
✔ Less code
✔ Cleaner syntax
4️⃣ Readonly Properties
Cannot be modified after initialization.
5️⃣ Inheritance (extends)
One class can inherit another.
6️⃣ Method Overriding
7️⃣ super Keyword
Used to call parent class constructor or methods.
8️⃣ Implementing Interfaces
Classes can implement interfaces.
9️⃣ Static Properties & Methods
Belong to the class itself, not instances.
🔟 Abstract Classes
Used as a base class and cannot be instantiated.
🔑 Classes Summary
| Feature | Syntax |
|---|---|
| Class | class A {} |
| Constructor | constructor() |
| Inheritance | extends |
| Interface | implements |
| Access Control | public / private / protected |
| Static | static |
| Abstract | abstract |
⭐ Best Practices
✔ Use private/protected for encapsulation
✔ Prefer interfaces for contracts
✔ Use readonly for immutable data
✔ Keep classes small & focused
