Union types are used when a value can realistically be more than a single type.
For instance, an ID could easily be a number or a string depending on the database.
Union types allow you to specify exactly which types are legally allowed.
This adds flexibility without sacrificing strict type safety.
To define a union type, you use the pipe symbol (|) between the types.
It reads exactly like the logical "OR" operator in plain English.
It is incredibly useful for writing highly adaptable and reusable functions.
let statusCode: string | number;statusCode = 200; // Perfectly valid statusCode = "OK"; // Also perfectly valid
// statusCode = true; // Error! boolean is not allowed.
console.log("Status Code:", statusCode);
When using a union type in a function, you often need to check the actual type first.
This process is known as "Type Narrowing" and is essential for safety.
If you don't narrow the type, TypeScript restricts you to methods shared by both types.
function printId(id: number | string) {
if (typeof id === "string") {
console.log(id.toUpperCase()); // Safe to use string methods
} else {
console.log(id); // Must be a number here
}
}
printId(101);
printId("admin_user");
Union types prevent your application from breaking when handling unpredictable JSON responses.
Robust data handling leads to longer user sessions and lower bounce rates.
This technical stability signals high quality to search engine web crawlers.
type Result = "success" | "error" | "loading";let currentStatus: Result = "success"; // Restricts variables to very specific literal string values!
console.log("Current Status:", currentStatus);
Which symbol is used to create a Union Type in TypeScript?
Union types make your code incredibly versatile without relying on any.
Always remember to use type narrowing when working with them inside functions.
Next up, we will deep dive into strongly typing your Functions!