TypeScript Union Types

TypeScript tutorial

🔀 TypeScript Union Types

In TypeScript Union Types let a variable, parameter, or return value be one of several types.

They are written using the pipe symbol |.

📌 Think of union as ORthis OR that


1️⃣ Basic Union Type

let value: number | string;

value = 10; // ✅
value = “Ten”; // ✅
value = true; // ❌ Error


2️⃣ Union Types with Functions

function printId(id: number | string) {
console.log(id);
}
printId(101);
printId(“A101”);


3️⃣ Union Types with Arrays

Array elements can be more than one type.

let data: (number | string)[] = [1, "two", 3];

4️⃣ Union Types with Objects

type Admin = {
role: "admin";
permissions: string[];
};
type User = {
role: “user”;
email: string;
};

type Person = Admin | User;


5️⃣ Type Narrowing (Very Important ⭐)

TypeScript requires you to check the type before using it.

Using typeof

function process(value: number | string) {
if (typeof value === "string") {
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}
}

6️⃣ Union with Literal Types

Restrict values to exact options.

type Status = "pending" | "approved" | "rejected";

let orderStatus: Status = “approved”;


7️⃣ Union Types with null / undefined

Very common in real projects.

let username: string | null = null;

function getName(name?: string) {
console.log(name ?? “Guest”);
}


8️⃣ Discriminated Unions ⭐⭐

Use a common literal property to safely narrow types.

type Circle = {
kind: "circle";
radius: number;
};
type Rectangle = {
kind: “rectangle”;
width: number;
height: number;
};

type Shape = Circle | Rectangle;

function area(shape: Shape) {
if (shape.kind === “circle”) {
return Math.PI * shape.radius ** 2;
} else {
return shape.width * shape.height;
}
}


9️⃣ Union vs Intersection

| Feature | Union (|) | Intersection (&) |
|—-|—-|—-|
| Meaning | OR | AND |
| Values | One of many | Must satisfy all |
| Use Case | Flexible inputs | Combine features |


🔑 Union Types Summary

Use Case Example
Variable string
Function Param (a: number
Array (number
Literal “yes”
Null Safety `string
Discriminated kind: "type"

⭐ Best Practices

✔ Always narrow union types
✔ Use discriminated unions for objects
✔ Prefer union types over any
✔ Combine with literal types for safety

You may also like...