21. How do you define and work with union types and intersection types in TypeScript?

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.

devFlipCards 2025

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.