A Union Type means a value can be one of several types.
β Syntax
let value: string | number;
value = "Hello"; // β
OK
value = 123; // β
OK
value = true; // β Errorβ Example: Function with Union Type
function printId(id: number | string) {
console.log("Your ID is: " + id);
}
printId(101); // OK
printId("A102"); // OKπ Type Narrowing with Union Types
When you use union types, TypeScript requires you to narrow the type before performing operations that are specific to one type.
function formatInput(input: string | number) {
if (typeof input === "string") {
return input.toUpperCase(); // β
TypeScript knows it's a string
}
return input.toFixed(2); // β
input is number here
}π§ͺ Union in Object Properties
type Status = "loading" | "success" | "error";
function handleStatus(status: Status) {
if (status === "loading") {
console.log("Loading...");
} else if (status === "success") {
console.log("Success!");
} else {
console.log("Something went wrong.");
}
}β This is also called a string literal union β often used for enums or state machines.
π§± Union Types with Arrays
let data: (string | number)[] = ["Alice", 25, "Bob", 42];
data.forEach(item => {
if (typeof item === "string") {
console.log(item.toUpperCase());
} else {
console.log(item.toFixed(1));
}
});π§ Use Cases
Use Case | Why Union Types Help |
|---|---|
Form inputs | Value can be `string |
API responses (success/error) | Response can be two different shapes |
Optional fields | Value can be `type |
Status indicators | `βloadingβ |
π« Pitfall to Avoid
You cannot directly use methods unless you first narrow the type:
function getLength(input: string | number) {
return input.length; //β Error: 'length' not available on number
}
// Use narrowing:
if (typeof input === "string") {
return input.length; // β
}