"Testing1"
TypeScript Union Types
TypeScript: Union Types
Union types allow a variable to hold more than one possible type.
What Are Union Types?
Sometimes, a value isn’t limited to just one kind of data.
For example, a variable might be a number or a string — depending on how it's used.
Instead of locking it to just one type, TypeScript gives you a way to say:
“This can be this type, that type, or even more.”
That’s where union types come in.
How Do You Use Them?
You combine types with a vertical bar | (known as the "pipe" symbol):
let id: string | number;
This means id can be either a string or a number.
id = "A123"; // Id = 456; // id = true; // Error! Not allowed
When Are Union Types Helpful?
- Handling flexible inputs (e.g., a form field that accepts both text and numbers)
- Dealing with APIs that return multiple possible types
- Accepting optional values like null or undefined
let result: number | null; result = null; // okay Result = 95; // also okay
In Functions Too
Union types work with function parameters as well:
function display(value: string | number) {
console.log("Value:", value);
}
This function can accept either a number or a string as input.
Quick Reminder
When using a union, you often need to check what type it currently holds before doing certain actions.
function printLength(item: string | string[]) {
if (typeof item === "string") {
console.log(item.length);
} else {
console.log(item.join(", ").length);
}
}
Prefer Learning by Watching?
Watch these YouTube tutorials to understand TYPESCRIPT Tutorial visually:
What You'll Learn:
- 📌 Typescript tutorial for beginners #8 Union types
- 📌 13 Union Type - TypeScript Tutorial for Beginners