乐闻世界logo
搜索文章和话题

How to Distinguish Between Union and Intersection Types in TypeScript?

2024年7月4日 22:56

Union and Intersection types in TypeScript are two powerful features of the type system that allow combining multiple types. I will now provide a detailed explanation of their differences and how to use them, with examples.

Union Types

Union types allow a value to be any one of several types. In TypeScript, we define union types using the pipe symbol |. They are used to represent variables that can hold values of different types.

Example:

Consider a function that accepts parameters which can be either numbers or strings. We can define the parameter type as follows:

typescript
function printId(id: number | string) { if (typeof id === 'number') { console.log(`Your ID is: ${id}.`); } else { console.log(`Your ID is: ${id}.`); } } printId(101); // Output: Your ID is: 101. printId('202'); // Output: Your ID is: 202.

In this example, the id parameter is a union type, which can be either number or string.

Intersection Types

Intersection types require a value to satisfy multiple types. In TypeScript, we define intersection types using the & symbol. They are typically used to combine properties from multiple types, allowing a variable to have all the properties of these types.

Example:

Suppose we have two interfaces, Employee and Manager:

typescript
interface Employee { employeeId: number; age: number; } interface Manager { stockPlan: boolean; } type EmployeeManager = Employee & Manager; function promoteToManager(person: EmployeeManager) { console.log(`Employee ${person.employeeId} of age ${person.age} has been promoted and has a stock plan: ${person.stockPlan}`); } const newManager: EmployeeManager = { employeeId: 1234, age: 45, stockPlan: true }; promoteToManager(newManager);

In this example, EmployeeManager is an intersection type that combines the properties of Employee and Manager, so an EmployeeManager type object must have all properties from both types.

Summary

Union types are used to represent values that can belong to multiple types, suitable for variables with multiple possible types. Intersection types require values to satisfy multiple types simultaneously, ideal for scenarios involving type composition.

Understanding and distinguishing between these two types is essential for effectively using TypeScript's type system, enabling developers to write safer and more readable code.

标签:TypeScript