union (A | B) کا مطلب "A یا B" ہے۔ intersection (A & B) کا مطلب "A اور B ایک ساتھ" ہے۔
ts
// Union — value is one of several types
type Status = "loading" | "success" | "error"; // string literal union
let s: Status = "loading"; // only these three allowed
function id(x: string | number) { /* x is string OR number */ }
unions کے ساتھ کام کرنا: آپ صرف مشترک چیزوں کو استعمال کر سکتے ہیں
ts
function format(x: string | number) {
// x.toFixed(2); // ❌ toFixed doesn't exist on string
if (typeof x === "number") return x.toFixed(2); // ✅ narrowed to number
return x.toUpperCase(); // ✅ here it's a string
}
جب تک آپ union کو تنگ نہ کریں، آپ صرف وہی ممبرز کو access کر سکتے ہیں جو union کے ہر ممبر پر موجود ہوں — compiler آپ کو محفوظ رکھتا ہے۔
Intersection — شکلوں کو یکجا کریں
ts
type Name = { name: string };
type Age = { age: number };
type Person = Name & Age; // must have BOTH name and age
const p: Person = { name: "Ann", age: 30 }; // both required
Intersections آبجیکٹ اقسام کو compose/ملانے کے لیے بہترین ہیں (مثال کے طور پر، موجودہ قسم میں props شامل کرنا)۔
یہ اہم کیوں ہے
Unions "متعدد امکانات میں سے ایک" کو ماڈل کرتے ہیں — محفوظ state modeling کی بنیاد (مثلاً reducer state کے لیے discriminated unions)، function overloads، اور nullable اقسام (T | null)۔
Intersections اقسام کو یکجا کرتے ہیں۔
مل کر، یہ TypeScript کے type system کو اتنا expressive بناتے ہیں کہ اصل ڈیٹا کو بالکل ظاہر کیا جا سکے۔
