Hi, I'm Jacob. Enjoying devFlipCards? Buy me a coffee

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.

Struggling to find common date to meet with your friends? Try our new tool
commondate.xyz