Intersection types and union types are both powerful features in TypeScript that allow developers to work with multiple types. Understanding the differences between them is crucial for writing robust and maintainable code. While both types enable more flexible type definitions, they serve different purposes and have distinct behaviors.
Intersection types combine multiple types into one. A value of an intersection type must satisfy all the types it intersects. This means that the value must have all the properties of the intersected types.
type Person = {
name: string;
age: number;
};
type Employee = {
employeeId: number;
};
type EmployeePerson = Person & Employee;
const john: EmployeePerson = {
name: "John Doe",
age: 30,
employeeId: 1234
};
In this example, the type EmployeePerson is an intersection of Person and Employee. The object john must have properties from both types.
Union types allow a value to be one of several types. A value of a union type can be any one of the types it includes, but it does not need to satisfy all of them.
type StringOrNumber = string | number;
let value: StringOrNumber;
value = "Hello"; // valid
value = 42; // valid
value = true; // Error: Type 'boolean' is not assignable to type 'StringOrNumber'
Here, the type StringOrNumber can be either a string or a number. The variable value can hold either type, but not both at the same time.
| Feature | Intersection Types | Union Types |
|---|---|---|
| Definition | Combines multiple types into one | Allows a value to be one of several types |
| Usage | Requires all properties from combined types | Requires only one of the types |
| Syntax | & | | |
| Example | type A & B |
type A | B |
In summary, while intersection types and union types both enhance TypeScript's type system, they serve different purposes. Understanding when and how to use each type can significantly improve code quality and maintainability.