Generic Classes की जानकारी
In this page:
class ClassName<T> {
property: T;
constructor(value: T) {
this.property = value;
}
}
Basic Generic Class
एक class एक type parameter declare कर सकती है और इसे अपनी properties और methods के लिए उपयोग कर सकती है, इसलिए वही class definition instantiate होने पर supply की गई किसी भी type के लिए specialized objects produce करती है।
उदाहरण: Basic Generic Class
class Box<T> {
constructor(public value: T) {}
}
const box = new Box<string>("hello");
console.log(box.value);
Generic Stack
एक generic class stack या queue जैसी reusable data structures implement कर सकती है जबकि अंदर stored items की exact type preserve करते हुए, any में fall back करने और हर read पर type safety खोने के बजाय।
उदाहरण: Generic Stack
class Stack<T> {
private items: T[] = [];
push(item: T) { this.items.push(item); }
pop(): T | undefined { return this.items.pop(); }
}
const stack = new Stack<number>();
stack.push(1);
stack.push(2);
console.log(stack.pop());
Generic Class Methods
एक generic class के अंदर methods class के अपने type parameter को consistent input और output typing के लिए उपयोग कर सकते हैं, इसलिए एक generic Stack<T> पर push और pop जैसे operations हमेशा सहमत होते हैं कि T क्या है।
उदाहरण: Generic Class Methods
class Stack<T> {
private items: T[] = [];
push(item: T): void { this.items.push(item); }
peek(): T { return this.items[this.items.length - 1]; }
}
const s = new Stack<string>();
s.push("top");
console.log(s.peek());
Objects के साथ Generic Classes
Generic classes एक type alias या interface को type argument के रूप में उपयोग करके complex object types store कर सकती हैं, जो exactly वही तरीके से काम करता है जैसे number या string जैसी एक simple type supply करना।
उदाहरण: Generic Classes with Objects
interface User { name: string; }
class Repository<T> {
private items: T[] = [];
add(item: T) { this.items.push(item); }
all(): T[] { return this.items; }
}
const users = new Repository<User>();
users.add({ name: "Farhan" });
console.log(users.all());
Generic Classes में Type Inference
TypeScript अक्सर new को pass किए गए constructor arguments से सीधे एक class का type parameter infer कर सकता है, इसलिए callers को हमेशा type argument explicitly लिखना नहीं पड़ता।
उदाहरण: Type Inference in Generic Classes
class Box<T> {
constructor(public value: T) {}
}
const box = new Box(123); // T inferred as number
console.log(box.value);
- type argument भूल जाना, जैसे
new Stack(), इसलिए typeunknownबन जाता है या बहुत loosely infer होता है। - class के type parameter को एक static member में उपयोग करना, जैसे
static create(x: T), जब staticsTको reference नहीं कर सकते। - एक empty
Stack<T>से pop करना और बिना check किए result उपयोग करना, क्योंकिpop()T | undefinedreturn करता है।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: