Generic Interfaces की जानकारी
In this page:
interface InterfaceName<T> {
property: T;
method(param: T): T;
}
Basic Generic Interface
एक interface एक type parameter declare कर सकता है और इसे अपने property types के अंदर उपयोग कर सकता है, एक interface definition को कई अलग-अलग concrete shapes describe करने देते हुए depending on क्या type supply की गई है।
उदाहरण: Basic Generic Interface
interface Box<T> {
value: T;
}
const numberBox: Box<number> = { value: 42 };
console.log(numberBox);
Generic Response Interface
एक generic response interface common metadata — जैसे एक status code या timestamp — को हर उपयोग में fixed रख सकता है, जबकि actual data payload की type को हर API endpoint के हिसाब से vary होने देता है।
उदाहरण: Generic Response Interface
interface ApiResponse<T> {
status: number;
data: T;
}
const res: ApiResponse<string> = { status: 200, data: "OK" };
console.log(res);
Arrays के साथ Generic Interfaces
एक interface एक generic parameter उपयोग कर सकता है एक collection में items की type define करने के लिए, इसलिए एक single Box<T>-style interface numbers के एक box, strings के एक box, या किसी और चीज़ के एक box को describe कर सकता है।
उदाहरण: Generic Interfaces with Arrays
interface Box<T> {
items: T[];
}
const box: Box<number> = { items: [1, 2, 3] };
console.log(box);
Functions के साथ Generic Interfaces
Generic interfaces उन functions को describe कर सकते हैं जिनके input और output types साथ vary होते हैं, जो callback shapes को type करने के लिए उपयोगी है जिन्हें अलग-अलग call sites में flexible रहने की ज़रूरत है।
उदाहरण: Generic Interfaces with Functions
interface Transformer<T, U> {
transform: (input: T) => U;
}
const toLength: Transformer<string, number> = {
transform: (s) => s.length,
};
console.log(toLength.transform("hello"));
Objects के साथ Generic Interfaces
एक generic interface एक reusable object type contain कर सकता है जो caller select करता है, जो सिर्फ इसलिए near-identical interfaces बार-बार लिखने से बचाता है क्योंकि contained data type बदलती है।
उदाहरण: Generic Interfaces with Objects
interface Container<T> {
content: T;
}
const container: Container<{ id: number }> = { content: { id: 1 } };
console.log(container);
- Box को type argument के बिना लिखना, जैसे
const b: Box = { value: 1 }, जो error देता है क्योंकिBox<T>को एक चाहिए। - यह मान लेना कि
Box<string>औरBox<number>interchangeable हैं, जब वे अलग types हैं। interface Box<T> { value: any }declare करना और कभीTउपयोग न करना, इसलिए parameter का कोई असर नहीं पड़ता।
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: