A union type is a powerful feature in TypeScript that allows a variable to hold multiple types of values. This flexibility is particularly useful in scenarios where a function or a variable can accept different types of input. By defining a union type, developers can create more robust and type-safe applications. In this response, we will explore the definition of union types, practical examples, best practices, and common mistakes to avoid.
In TypeScript, a union type is defined using the pipe (`|`) operator. This operator combines multiple types into a single type, enabling a variable to accept any one of the specified types. For instance, if you want a variable to be either a string or a number, you can define it as follows:
let value: string | number;
Here are some practical examples demonstrating the use of union types:
Consider a function that accepts either a string or a number as an argument:
function formatValue(value: string | number): string {
return typeof value === 'string' ? value.trim() : value.toFixed(2);
}
In this example, the function checks the type of the input and formats it accordingly, demonstrating how union types can enhance type safety and clarity in function parameters.
Union types can also be used in object properties. For instance:
interface User {
id: number;
name: string;
role: 'admin' | 'user';
}
In this case, the `role` property can only be either 'admin' or 'user', ensuring that the application logic remains consistent and predictable.
In conclusion, union types are a valuable feature in TypeScript that enhance the flexibility and safety of your code. By understanding how to define and use them effectively, you can write more robust applications while avoiding common pitfalls.