Generic Functions की जानकारी
In this page:
function name<T>(param: T): T {
return param;
}
name<type>(value);
एक Generic Function बनाना
function name के बाद एक type parameter डालें और इसे parameter और return types में उपयोग करें; यह actually input type को output type से connect करता है बजाय function को हर concrete type के लिए अलग से लिखने के।
उदाहरण: Creating a Generic Function
function identity<T>(value: T): T {
return value;
}
console.log(identity<number>(10));
Arrays के साथ Generic Functions
Generic functions arrays accept कर सकते हैं और elements return कर सकते हैं जबकि उनका element type preserve करते हुए, इसलिए function को एक string[] पर call करना अब भी एक string ही देता है, कोई ऐसी value नहीं जिसे TypeScript को any तक widen करना पड़े।
उदाहरण: Generic Functions with Arrays
function firstElement<T>(arr: T[]): T {
return arr[0];
}
console.log(firstElement(["a", "b", "c"]));
Generic Arrow Functions
Arrow functions भी generic type parameters declare कर सकते हैं, और compact utility functions जैसे एक generic identity या comparator के लिए उपयोगी हैं जिन्हें छोटा लेकिन फिर भी पूरी तरह type-safe रहना चाहिए।
उदाहरण: Generic Arrow Functions
const identity = <T,>(value: T): T => value;
console.log(identity(99));
Objects के साथ Generic Functions
Generic functions उन्हें pass किए गए objects का exact type preserve कर सकते हैं, इसलिए एक function जो सिर्फ एक value forward या wrap करता है वह accidentally उस value के shape के बारे में useful information erase नहीं करता।
उदाहरण: Generic Functions with Objects
function wrap<T>(value: T): { data: T } {
return { data: value };
}
console.log(wrap({ name: "Nia" }));
Explicit Type Arguments
आप explicitly एक type argument provide कर सकते हैं (जैसे identity<string>(x)) जब आप intended type को clear बनाना चाहें, या जब TypeScript का inference genuinely इसे arguments से determine न कर सके।
उदाहरण: Explicit Type Arguments
function identity<T>(value: T): T {
return value;
}
console.log(identity<string>("explicit"));
- type parameter को गलत जगह रखना, जैसे
function<T> identity(value: T), जब यह function name के बाद जाता है:identity<T>। - एक generic parameter उपयोग करना लेकिन parameters या return type में कभी
Tउपयोग न करना, इसलिए यह कुछ नहीं जोड़ता। - एक
.tsxfile मेंconst f = <T>(x: T) => xलिखना, जो JSX के रूप में parse होता है;<T,>या एक function declaration उपयोग करें।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: