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:
type StringOrNumber = string | number;function displayValue(value: StringOrNumber) {if (typeof value === "string") {console.log("String value:", value.toUpperCase());} else {console.log("Number value:", value.toFixed(2));}}displayValue("Hello"); // String value: HELLOdisplayValue(42); // Number value: 42.00
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.
type Person = {name: string;age: number;};type Employee = {employeeId: number;department: string;};type EmployeeProfile = Person & Employee;const profile: EmployeeProfile = {name: "Amir",age: 30,employeeId: 1234,department: "Development"};console.log(profile);
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:
type SuccessResponse = {status: "success";data: any;};type ErrorResponse = {status: "error";error: string;};type ApiResponse = SuccessResponse | ErrorResponse;function handleResponse(response: ApiResponse) {if (response.status === "success") {console.log("Data:", response.data);} else {console.log("Error:", response.error);}}handleResponse({ status: "success", data: { id: 1, name: "Test" } }); // Data: { id: 1, name: "Test" }handleResponse({ status: "error", error: "Not found" }); // Error: Not found
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.