Union types allow a variable to be assigned multiple types. They can be defined using the |
operator. On the other hand, intersection types combine multiple types into one that contains the properties of all types, using the &
operator.
Example of union types:
let value: string | number; value = 'Hello'; // OK value = 10; // OK value = true; // Error: not a string or number
Example of intersection types:
interface Person { name: string; age: number; } interface Employee { jobTitle: string; } let employee: Person & Employee = { name: 'John', age: 30, jobTitle: 'Developer' }; // 'employee' has properties from both 'Person' and 'Employee'
Union types are useful when a value can be one of several types, and intersection types are useful when you want to combine multiple interfaces or types into one.