Typescript Union & Intersection Types
In TypeScript, Union and Intersection types are powerful tools for creating flexible and precise type definitions.
In TypeScript, Union and Intersection types are powerful tools for creating flexible and precise type definitions. They allow you to define types that can accept multiple types of values (union) or combine multiple types into a single type (intersection). Here’s a breakdown of how each works and examples to illustrate their use.
Union Types
A Union type allows a value to be one of several types. You create a union type by listing multiple types, separated by a pipe (|) symbol. This is useful when a variable can hold more than one type of value.
Example:
In this example, StringOrNumber can be either a string or a number. The function displayValue checks the type of the value and handles it accordingly.
Intersection Types
An Intersection type combines multiple types into one. A variable of an intersection type must satisfy all combined types simultaneously. You create an intersection type by listing multiple types, separated by an ampersand (&) symbol. This is useful when you want an object to have multiple properties from different types.
In this example, EmployeeProfile combines the Person and Employee types. An object of type EmployeeProfile must have all properties from both Person and Employee.
Advanced Example: Union and Intersection Together
You can also combine Union and Intersection types to create complex types.
Example:
In this example, ApiResponse is a union of SuccessResponse and ErrorResponse, allowing it to be either type depending on the response status.
Summary
Union (
|): Accepts multiple types of values, allowing flexibility in variable values.Intersection (
&): Combines multiple types into one, requiring all properties from each type.