In TypeScript, a union type allows you to define a type that can be one of several types. You can define a union type using the vertical bar ‘|‘ between the types you want to create a union of.
Here’s an example of defining a union type:
type StringOrNumber = string | number;
In this example, we’ve created a type ‘StringOrNumber‘ that can be either a ‘string‘ or a ‘number‘.
To use a union type, you can apply it to a variable, a function parameter, or a function return type. Here’s how to use the ‘StringOrNumber‘ type we defined earlier:
function processValue(value: StringOrNumber) {
if (typeof value === "string") {
console.log("Processing a string:", value.toUpperCase());
} else if (typeof value === "number") {
console.log("Processing a number:", Math.sqrt(value));
} else {
// This case should never be reached
console.log("Unknown value:", value);
}
}
const input1: StringOrNumber = "Hello, TypeScript!";
const input2: StringOrNumber = 64;
processValue(input1); // Processing a string: HELLO, TYPESCRIPT!
processValue(input2); // Processing a number: 8
In this example, we have a function ‘processValue‘ that takes a ‘StringOrNumber‘ parameter. Inside the function, we use a type guard (the ‘typeof‘ check) to determine if the input value is a ‘string‘ or a ‘number‘. Depending on the type, we perform different operations, such as converting the string to upper case or calculating the square root.
Notice that if you try to assign a value of an incompatible type to a variable with a union type, TypeScript will show a compile-time error:
const input3: StringOrNumber = true; // Error: Type 'boolean' is not assignable to type 'StringOrNumber'