In TypeScript, a union type is a type that allows a value to be one of several specified types. It’s useful when you want to allow a variable to have multiple potential types. You define a union type using the vertical bar (|
) to separate each type.
Example of Union Type
let data: string | number;
data = "Hello World"; // OK
data = 100; // OK
data = true; // Error: Type 'boolean' is not assignable to type 'string | number'.
In this example, the variable data can be either a string
or a number
, but not any other type like boolean
.
Usage in Functions
function format(input: string | number): string {
if (typeof input === "string") {
return input.toUpperCase();
} else {
return input.toFixed(2);
}
}
console.log(format("Hello World")); // Output: "HELLO WORLD"
console.log(format(120)); // Output: "120.00"
Here, the format
function accepts either a string
or a number
as its input and handles each type appropriately.
Union Types with Objects
type Cat = { name: string; purrs: boolean };
type Dog = { name: string; barks: boolean };
type Pet = Cat | Dog;
function makeSound(pet: Pet): string {
if ("purrs" in pet) {
return pet.name + " purrs.";
} else {
return pet.name + " barks.";
}
}
const cat: Cat = { name: "Pussy", purrs: true };
const dog: Dog = { name: "Tiger", barks: true };
console.log(makeSound(cat)); // Output: "Pussy purrs."
console.log(makeSound(dog)); // Output: "Tiger barks."