Union types in TypeScript are a powerful feature that allows developers to define a variable that can hold multiple types of values. This flexibility enhances type safety while enabling more dynamic programming patterns. By using union types, developers can create more robust applications that can handle various data types without sacrificing type integrity.
In TypeScript, a union type is defined using the pipe (`|`) symbol. This allows a variable to accept values of different types, which can be particularly useful in scenarios where a function can return different types based on certain conditions.
To define a union type, you simply specify the types you want to combine. Here’s a basic example:
let value: string | number;
value = "Hello"; // valid
value = 42; // valid
value = true; // Error: Type 'boolean' is not assignable to type 'string | number'
Consider a function that processes user input, which can either be a string or a number. Using a union type allows you to handle both cases seamlessly:
function processInput(input: string | number) {
if (typeof input === 'string') {
console.log("String input: " + input.toUpperCase());
} else {
console.log("Number input: " + (input * 2));
}
}
processInput("hello"); // Output: String input: HELLO
processInput(10); // Output: Number input: 20
In conclusion, union types in TypeScript provide a flexible way to handle multiple types within a single variable. By following best practices and being aware of common pitfalls, developers can leverage union types to create safer, more maintainable code.