Multiple Type Parameters की जानकारी
In this page:
function name<T, U>(first: T, second: U): [T, U] {
return [first, second];
}
दो Type Parameters
Commas से separated multiple type parameters declare करें (जैसे <T, U>) ताकि हर एक same generic function, class, या interface के अंदर एक अलग, independent type represent कर सके।
उदाहरण: Two Type Parameters
function pair<T, U>(first: T, second: U): [T, U] {
return [first, second];
}
console.log(pair("id", 42));
Functions में Multiple Parameters
Separate type parameters कई arguments और return type के बीच relationships describe कर सकते हैं — उदाहरण के लिए, एक merge function जिसका result type दोनों input object types को साथ combine करता है।
उदाहरण: Multiple Parameters in Functions
function merge<T, U>(a: T, b: U): T & U {
return { ...a, ...b };
}
console.log(merge({ name: "A" }, { age: 20 }));
Transformations के साथ Multiple Parameters
दो type parameters खासकर उपयोगी हैं जब एक function एक type को दूसरी में transform करता है, जैसे एक supplied conversion function उपयोग करके T के एक array को U के array में map करना।
उदाहरण: Multiple Parameters with Transformations
function mapArray<T, U>(items: T[], fn: (item: T) => U): U[] {
return items.map(fn);
}
console.log(mapArray([1, 2, 3], (n) => n.toString()));
Interfaces में Multiple Parameters
Interfaces के multiple generic parameters हो सकते हैं जब वे data के distinct pieces के बीच relationships describe करते हों, जैसे एक generic lookup या cache shape में एक key type और एक value type।
उदाहरण: Multiple Parameters in Interfaces
interface Cache<K, V> {
get(key: K): V | undefined;
}
const cache: Cache<string, number> = {
get: (key) => (key === "x" ? 1 : undefined),
};
console.log(cache.get("x"));
Classes में Multiple Parameters
Generic classes genuinely अलग-अलग types की values को साथ store करने के लिए multiple type parameters उपयोग कर सकती हैं, जैसे एक Pair<K, V> class जो K type की एक value और V type की दूसरी रखती है।
उदाहरण: Multiple Parameters in Classes
class Pair<K, V> {
constructor(public key: K, public value: V) {}
}
const pair = new Pair<string, number>("age", 30);
console.log(pair.key, pair.value);
- दो arguments के लिए एक
Tउपयोग करना, जैसेmerge<T>(a: T, b: T), जो दोनों को same type होने के लिए force करता है। - यह भूल जाना कि
<T, U>को दोनों supply करने की ज़रूरत पड़ती है अगर आप explicit arguments देते हैं, क्योंकि सिर्फ एक supply करना एक error है जब तक दूसरे का कोई default न हो। - एक generic से
{ ...a, ...b }return करना और सिर्फTdeclare करना, इसलिए result type मेंbसे properties शामिल नहीं होती।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: