Generics का परिचय
In this page:
function name<T>(param: T): T {
return param;
}
Generics क्यों उपयोगी हैं
Generics एक function या class को बिना actually pass की गई specific type के बारे में information खोए कई अलग-अलग types के साथ काम करने देते हैं, any उपयोग करने के विपरीत, जो उस type information को पूरी तरह फेंक देता है।
उदाहरण: Why Generics Are Useful
function identity<T>(value: T): T {
return value; // keeps the exact input type, unlike "any"
}
console.log(identity<string>("hello"), identity<number>(42));
Type Parameters
T जैसा एक type parameter एक concrete type के लिए एक placeholder है जो generic code actually उपयोग होने पर supply किया जाता है, उसी तरह जैसे एक function parameter call time पर supply किए गए एक concrete value के लिए एक placeholder है।
उदाहरण: Type Parameters
function wrapInArray<T>(value: T): T[] {
return [value];
}
console.log(wrapInArray(5), wrapInArray("hi"));
Type Inference
TypeScript अक्सर supplied argument से एक generic type अपने आप infer करता है, इसलिए explicit type arguments सिर्फ तब ज़रूरी होते हैं जब compiler genuinely intended type अपने आप figure out न कर सके।
उदाहरण: Type Inference
function identity<T>(value: T): T {
return value;
}
console.log(identity(42)); // T inferred as number, no explicit argument needed
Generic Arrays
Generics अक्सर arrays के साथ combine किए जाते हैं element type describe करने के लिए जबकि function को numbers, strings, या किसी भी दूसरी type के arrays में reusable रखते हुए, यह सब उसी generic implementation के through।
उदाहरण: Generic Arrays
function firstItem<T>(items: T[]): T {
return items[0];
}
console.log(firstItem([1, 2, 3]), firstItem(["a", "b"]));
Generic Type Aliases
Type aliases के भी type parameters हो सकते हैं, एक object shape को अलग-अलग data types plug किए जाने के साथ reusable बनाते हुए — उदाहरण के लिए, एक generic ApiResponse<T> shape जो काम करती है चाहे T एक User हो, एक Product हो, या कुछ भी हो।
उदाहरण: Generic Type Aliases
type ApiResponse<T> = {
data: T;
status: number;
};
const response: ApiResponse<string> = { data: "OK", status: 200 };
console.log(response);
- generic के बजाय
anyउपयोग करना, जैसेfunction id(v: any): any, जो input और return types के बीच connection खो देता है। - यह भूल जाना कि
Tसिर्फ एक placeholder है, औरT.lengthयाnew T()लिखना जैसे यह एक असली value हो। - explicit type arguments pass करना जो argument से match न करें, जैसे
identity<string>(42), जो एक error है।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: