Generic Constraints की जानकारी
In this page:
function name<T extends ConstraintType>(param: T): T {
return param;
}
Basic Generic Constraint
एक generic parameter एक object shape extend कर सकता है (उदाहरण के लिए, T extends { length: number }) यह guarantee करने के लिए कि उपयोग की जा रही कोई भी type में कम से कम वे required properties हैं जिन पर function की body भरोसा करती है।
उदाहरण: Basic Generic Constraint
function printLength<T extends { length: number }>(value: T): void {
console.log(value.length);
}
printLength("hello");
printLength([1, 2, 3]);
Primitive Types के साथ Constraints
एक type parameter को number या string जैसी एक primitive type तक constrain किया जा सकता है, callers को क्या supply करने की permission है यह limit करते हुए जबकि function को अब भी उस constraint के अंदर की values में generic रखते हुए।
उदाहरण: Constraints with Primitive Types
function double<T extends number>(value: T): number {
return value * 2;
}
console.log(double(21));
Object Shapes के साथ Constraints
Object constraints generic functions को required properties access करने देते हैं जबकि caller के actual argument को constraint द्वारा specify की गई चीज़ों से beyond additional, unrelated properties रखने की permission भी देते हैं।
उदाहरण: Constraints with Object Shapes
function printName<T extends { name: string }>(obj: T): void {
console.log(obj.name);
}
printName({ name: "Tom", age: 30 }); // extra properties allowed
Interface-Based Constraints
Interfaces reusable shapes प्रदान करते हैं जो generic constraints के रूप में उपयोग किए जा सकते हैं, इसलिए एक constraint एक बार define किया जा सकता है और कई अलग-अलग generic functions या classes में reuse किया जा सकता है बजाय एक inline object shape बार-बार repeat करने के।
उदाहरण: Interface-Based Constraints
interface HasId {
id: number;
}
function printId<T extends HasId>(item: T): void {
console.log(item.id);
}
printId({ id: 7, name: "Item" });
Constraints क्यों मायने रखते हैं
Constraints type safety छोड़े बिना flexibility प्रदान करते हैं — वे generic code को types की एक wide range accept करने देते हैं जबकि अब भी compiler को guarantee देते हैं कि certain properties या methods present होंगे।
उदाहरण: Why Constraints Matter
function getLength<T extends { length: number }>(value: T): number {
return value.length; // guaranteed to exist because of the constraint
}
console.log(getLength("hello"), getLength([1, 2]));
- एक unconstrained
Tपरvalue.lengthउपयोग करना, जो error देता है क्योंकि TypeScript को नहीं पता किTके पास वह property है। - यह सोचना कि एक constraint returned type बदल देता है, जब
T extends { length: number }अब भीTreturn करता है, constraint type नहीं। - एक argument pass करना जिसमें required shape नहीं है, जैसे
printLength(42), जो fail होता है क्योंकिnumberके पास कोईlengthनहीं है।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: