Classes aur Objects
Ek class data (properties) ko un functions (methods) ke sath jorti hai jo usper kaam karte hain — bilkul JavaScript jaisa hi idea, lekin TypeScript access modifiers add karta hai jo control karte hain ke ek property ya method kahan se istemal ki ja sakti hai.
main.ts
Khud try karo →class Dog {
name: string;
private age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
bark(): string {
return `${this.name} says Woof! (age ${this.age})`;
}
}
const rex = new Dog("Rex", 3);
console.log(rex.name);
console.log(rex.bark());Output
Rex Rex says Woof! (age 3)
public, private, protected, aur readonly
- public default hota hai — kahin se bhi accessible hai, class ke bahar se bhi
- private sirf class ke andar se hi accessible hota hai — rex.age, Dog ke bahar ek compile error hoga
- protected private jaisa hi hai, lekin subclasses se bhi accessible hota hai
- readonly ko in mein se kisi ke bhi sath combine kiya ja sakta hai, aur ise sirf ek baar set kiya ja sakta hai, usually constructor mein
Constructor shorthand
Har property ke liye this.name = name likhna dohrahat ban jaata hai — TypeScript aapko iske bajaye ek property ko seedha constructor ki parameter list mein declare aur assign karne deta hai.
main.ts
Khud try karo →class Point {
constructor(public x: number, public y: number) {}
toString(): string {
return `(${this.x}, ${this.y})`;
}
}
const p = new Point(3, 4);
console.log(p.toString());Output
(3, 4)
Aage: generics — ek aisa function ya type likhna jo kai types ke across kaam kare, type safety khoye baghair.