Union and intersection types are advanced features in TypeScript that allow you to create more flexible and expressive types.
Union Types
A union type allows you to declare a variable or parameter that can hold values of multiple types. To create a union type, you use the |
symbol to separate the types. For example, consider the following code:
function printId(id: number | string) {
console.log(`ID is: ${id}`);
}
printId(101); // Output: ID is: 101
printId("abc"); // Output: ID is: abc
Here, the printId
function takes a parameter called id
, which can be either a number
or a string
. When you call the function with a number
, it prints the number, and when you call it with a string
, it prints the string.
Union types are especially useful when working with APIs that can return multiple types of data. For example, consider the following code that fetches data from a remote API:
async function fetchData(): Promise<number | string> {
const response = await fetch("https://example.com/data");
const data = await response.json();
if (typeof data === "number") {
return data;
} else {
return data.message;
}
}
const result = await fetchData();
if (typeof result === "number") {
console.log(`The data is a number: ${result}`);
} else {
console.log(`The data is a string: ${result}`);
}
Here, the fetchData
function returns a Promise
that resolves to either a number
or a string
, depending on the response from the API. The result
variable can hold either type of data, so we use the typeof
operator to determine the type and print a message accordingly.
Intersection Types
An intersection type allows you to create a new type that combines the properties of two or more types. To create an intersection type, you use the &
symbol to join the types. For example, consider the following code:
interface Person {
name: string;
age: number;
}
interface Employee {
id: number;
department: string;
}
type EmployeeInfo = Person & Employee;
const employee: EmployeeInfo = {
name: "Alice",
age: 30,
id: 101,
department: "Sales",
};
Here, we have two interfaces Person
and Employee
, each with their own set of properties. We then create a new type EmployeeInfo
that combines the properties of both interfaces using the &
symbol. Finally, we create an object of type EmployeeInfo
and assign it to the employee
variable.
Intersection types are useful when you need to create a new type that has all the properties of two or more existing types. For example, you might use an intersection type to represent a user that has both personal information (such as name and age) and employment information (such as ID and department).