Chapter 6TypeScript~1 min read
Classes आणि OOP
TypeScript मधील Object-Oriented Programming
TypeScript मध्ये classes JavaScript पेक्षा अधिक powerful आहेत — access modifiers (public, private, protected), implements, abstract classes हे features आहेत.
Class with access modifiers
typescript
class BankAccount {
public owner: string; // सगळीकडून access
private balance: number; // फक्त class च्या आत
protected accountNo: string; // subclass मधूनही access
constructor(owner: string, initialBalance: number) {
this.owner = owner;
this.balance = initialBalance;
this.accountNo = "ACC" + Math.random().toString().slice(2, 8);
}
public deposit(amount: number): void {
this.balance += amount;
}
public getBalance(): number {
return this.balance;
}
}
const acc = new BankAccount("Avadhoot", 5000);
acc.deposit(1000);
console.log(acc.getBalance()); // 6000
console.log(acc.balance); // ❌ ERROR: privateImplements interface
typescript
interface Shape {
area(): number;
perimeter(): number;
}
class Rectangle implements Shape {
constructor(private width: number, private height: number) {}
area(): number {
return this.width * this.height;
}
perimeter(): number {
return 2 * (this.width + this.height);
}
}
const rect = new Rectangle(5, 3);
console.log(rect.area()); // 15
console.log(rect.perimeter()); // 16💡
Constructor मध्ये `private`/`public` keyword लावलं तर parameter आपोआप property बनतो — shorthand syntax. `constructor(private name: string)` म्हणजेच `this.name = name`.
✅ Key Points — लक्षात ठेवा
- ▸public — सर्वत्र accessible
- ▸private — class च्या आतच
- ▸protected — class + subclass
- ▸implements — interface follow करणे compulsory
- ▸Constructor shorthand: private param
0/9 chapters पूर्ण