TypeScriptBeginner
Union ও Intersection Types
Union (|) এবং intersection (&) — literal union, object combine এবং এদের পার্থক্য — বাংলায় উদাহরণসহ।
13টি অংশবাংলা ভাষায়
Union type (|) মানে যেকোনো একটি, আর intersection type (&) মানে সবগুলো একসাথে। এই দুই অপারেটর মিলেই TypeScript-এর শক্তির মূল ভিত্তি।
Union Type
type ID = string | number;
function formatId(id: ID): string {
return "ID: " + id;
}
console.log(formatId("a-1"));
console.log(formatId(42));Union with Literal Types
type PaymentStatus = "pending" | "paid" | "failed";
type Result = "success" | "error";
function show(status: PaymentStatus): void {
console.log(status);
}
show("paid");
// show("done"); // ❌ অনুমোদিত নয়Intersection Type
Union মানে অথবা (একটা), Intersection মানে এবং (সবকিছু)। Intersection দিয়ে object টাইপ মিশিয়ে নতুন টাইপ বানানো হয়।
type User = {
name: string;
};
type Admin = {
role: string;
};
type AdminUser = User & Admin;
const boss: AdminUser = {
name: "রহিম",
role: "admin",
};
// boss-এ name ও role দুইটিই বাধ্যতামূলকCombining Object Types
type BaseUser = {
id: number;
name: string;
};
type Premium = {
premium: true;
expiresAt: Date;
};
type PremiumUser = BaseUser & Premium;
const member: PremiumUser = {
id: 1,
name: "সুমন",
premium: true,
expiresAt: new Date("2026-12-31"),
};Union vs Intersection
| অপারেটর | অর্থ | উদাহরণ |
|---|---|---|
| | (Union) | যেকোনো একটি | string | number |
| & (Intersection) | সবগুলো একসাথে | User & Admin |
| | ব্যবহার | সীমিত অপশন | 'paid' | 'pending' |
| & ব্যবহার | কম্বাইন্ড object | Base & Extra |
Union নিয়ে কাজের কৌশল
union পাওয়ার পর কোনো প্রপার্টি ব্যবহার করতে TypeScript narrowing চায় — typeof, in বা kind (discriminated union) দিয়ে টাইপ সরু করতে হয়। পরের অধ্যায়ে বিস্তারিত।
শেষ প্যারায় নিজে practice করুন — কোড কপি করে নিজের এডিটরে চালিয়ে দেখুন।