Intersection के Types
In this page:
type Combined = TypeA & TypeB;
Basic Intersection Types
& operator दो या ज़्यादा types को combine करके एक intersection type बनाता है, जैसे A & B। Resulting type intersection में हर type द्वारा मांगी गई सब चीज़ एक साथ require करता है, सिर्फ उनमें से एक allow करने के बजाय।
उदाहरण: Basic Intersection Types
type A = { a: string };
type B = { b: number };
type AB = A & B;
const value: AB = { a: "x", b: 1 };
console.log(value);
Combining Object Types
Intersection types तब चमकते हैं जब एक object को कई separate, focused concepts से properties combine करनी हों, जैसे एक Timestamped type को एक Named type के साथ combine करना।
हर source type छोटा और independently reusable रहता है, जबकि intersection complete required shape assemble करता है।
उदाहरण: Combining Object Types
type Timestamped = { createdAt: string };
type Named = { name: string };
type Entry = Timestamped & Named;
const entry: Entry = { createdAt: "2024", name: "Log Entry" };
console.log(entry);
Intersection Types with Functions
Intersection types एक object की data structure को additional capabilities के साथ combine कर सकते हैं, जैसे एक plain data shape को specific methods जोड़ने वाले एक type के साथ intersect करना।
यह तब उपयोगी है जब एक object को एक साथ कई related groups की requirements satisfy करनी हों।
उदाहरण: Intersection Types with Functions
type Data = { value: number };
type Loggable = { log: () => void };
const item: Data & Loggable = {
value: 42,
log() { console.log(this.value); },
};
item.log();
Multiple Intersections
एक single intersection में दो से ज़्यादा types combine किए जा सकते हैं, और resulting type participating types में से हर एक द्वारा मांगी गई हर property require करता है। यह naturally scale होता है जब ज़्यादा shared concerns को एक single type पर layer करना हो।
उदाहरण: Multiple Intersections
type A = { a: string };
type B = { b: string };
type C = { c: string };
type ABC = A & B & C;
const value: ABC = { a: "1", b: "2", c: "3" };
console.log(value);
Intersection vs Union
याद रखने वाला key distinction यह है कि एक union का मतलब है कि एक value कई types में से किसी एक को satisfy कर सकती है, जबकि एक intersection का मतलब है कि एक value को combined types को simultaneously satisfy करना चाहिए।
दोनों को confuse करना confusing type errors का एक common source है, तो TypeScript data structures design करते समय यह difference समझना बहुत मायने रखता है।
उदाहरण: Intersection vs Union
type Union = string | number; // satisfies ANY one type
type Combo = { a: string } & { b: number }; // satisfies ALL types
let u: Union = 5;
let c: Combo = { a: "x", b: 1 };
console.log(u, c);
- जब आपको
&चाहिए तब|उपयोग करना, तो value को types में से सिर्फ एक की ज़रूरत होती है बजाय दोनों के। - Conflicting property types वाले types को combine करना, जैसे
string & number, जोneverदेता है। - एक
ABvalue बनाना जिसमें combined types में से एक की properties missing हों।
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: