🔀 TypeScript — Union Types: Combine Multiple Types into One
🧲 Introduction – What Are Union Types in TypeScript?
In TypeScript, union types allow a variable to hold multiple possible types. They are declared using the pipe (|
) symbol and are extremely useful when a variable, function parameter, or return value can be of more than one type.
🎯 In this guide, you’ll learn:
- What union types are and how they work
- Syntax and usage with variables, functions, and arrays
- How to narrow types using guards
- Common use cases and best practices
🔗 What Is a Union Type?
A union type allows you to specify that a value can be one of several types.
✅ Syntax:
let value: string | number;
value = "Hello"; // ✅
value = 123; // ✅
value = true; // ❌ Error: boolean not allowed
✅ Explanation:
The variable value
is allowed to be either a string
or a number
—but not any other type.
🔠 Union Type with Functions
Functions can accept parameters with union types for flexible input.
✅ Example:
function printId(id: number | string) {
console.log("ID:", id);
}
printId(101); // ✅ number
printId("A102"); // ✅ string
// printId(true); // ❌ Error
📐 Type Narrowing with Union Types
When using union types, you often need type narrowing to safely access properties or methods.
✅ Using typeof
:
function getLength(val: string | number) {
if (typeof val === "string") {
return val.length; // ✅ string method
}
return val.toString().length; // ✅ number converted to string
}
🧩 Union Types in Arrays
You can allow different types within an array or allow the array to be of one of several types.
1️⃣ Mixed array of values:
let items: (string | number)[] = ["apple", 10, "banana", 5];
2️⃣ Union of array types:
let values: string[] | number[];
values = ["a", "b", "c"];
values = [1, 2, 3];
// values = [1, "a"]; // ❌ Error
✅ Explanation: The array must be all strings or all numbers, not a mix.
📄 Union Type with Custom Aliases
Define more readable unions using type aliases:
type Status = "success" | "error" | "loading";
let currentStatus: Status = "success";
✅ Makes code easier to maintain and restricts values to a known set.
📦 Union Types with Objects
You can combine object types using unions too.
type Dog = { bark: () => void };
type Cat = { meow: () => void };
type Pet = Dog | Cat;
function speak(pet: Pet) {
if ("bark" in pet) {
pet.bark();
} else {
pet.meow();
}
}
✅ Explanation: Use the "property" in object
syntax to narrow union types of objects.
⚖️ Union vs Intersection Types
| Feature | Union (|
) | Intersection (&
) |
|———————-|———————————————|————————————————|
| Meaning | Value can be any one of the types | Value must satisfy all types simultaneously |
| Syntax | type A = B | C
| type A = B & C
|
| Flexibility | High | Strict |
| Use Case | Inputs, variations | Merging types or interfaces |
⚠️ Common Mistakes & How to Avoid Them
❌ Mistake | ✅ Solution |
---|---|
Accessing properties without checks | Use typeof , in , or custom guards |
Mixing incompatible union members | Avoid unrelated types in the same union |
Ignoring type narrowing | Always verify the type before using type-specific features |
💡 Best Practices
- ✅ Use union types for flexible function parameters and APIs
- ✅ Combine with type narrowing for safe access
- ✅ Use custom
type
aliases to improve readability - ✅ Keep unions simple and well-related
- ❌ Avoid unioning unrelated types unless necessary
📌 Summary – Recap & Next Steps
Union types are one of TypeScript’s most powerful features for working with flexible and dynamic inputs. They enable you to define safe variability in your code without sacrificing type safety.
🔍 Key Takeaways:
- Use
|
to allow multiple possible types - Always narrow the type before accessing specific properties
- Combine with type guards like
typeof
,instanceof
, orin
- Use aliases to make complex unions easier to understand
⚙️ Real-world relevance: Used in form validations, input types, API responses, event handling, and condition-based logic.
❓ FAQs – Union Types in TypeScript
❓ Can a union type include more than two types?
✅ Yes. Example: type Value = string | number | boolean
.
❓ Do union types exist at runtime?
❌ No. Union types are a compile-time feature in TypeScript only.
❓ How do I safely access members of a union type?
✅ Use type guards (typeof
, in
, instanceof
) to narrow the type before usage.
❓ Should I use a union or a custom interface?
📌 Use unions for flexible data structures and interfaces for structured, consistent objects.
❓ Can I use union types with enums or literals?
✅ Absolutely! Example: type ButtonType = "submit" | "reset" | "cancel"
.
Share Now :