Note: If you're new to TypeScript, check our Getting Started with TypeScript tutorial first.
TypeScript union and intersection types are a way to combine multiple data types. They help define variables that can be one of many types (union) or must satisfy all types (intersection).
Let's learn about the union and intersection types in detail.
TypeScript Union Type
A Union type allows a variable to be one of the multiple specified types. For example, let's define a variable value
of union type.
let value: string | number;
value = "hello"; // valid
value = 42; // also valid
Here, value
is a union type that can hold a string or a number. Notice that we've used the |
symbol to define a union type.
Note: The union type is like saying "a variable can be A or B".
Frequently Asked Questions
You can also use a union type in function parameters. For example,
function printId(id: number | string) {
console.log("ID:", id);
}
printId(101); // valid
printId("101A"); // valid
Output
ID: 101 ID: 101A
Here, printId()
uses union for its parameter. This allows id
to be either a number or a string.
TypeScript Intersection Type
An Intersection type merges multiple types into one. A value of this type must include all properties from each of the combined types.
You use the &
symbol to define an intersection type. For example,
type resultingType = typeA & typeB
Here, resultingType
must satisfy both typeA
and typeB
, meaning it must have all their required properties.
Example: TypeScript Intersection Type
type Name = { name: string };
type Age = { age: number };
type Person = Name & Age;
const person1: Person = {
name: "Alex",
age: 30
};
In this example, Person
is an intersection type formed by combining Name
and Age
. This means that any value of the type Person
must include both the name
and age
properties.
So, when we define person1
of the Person
type, it must contain both fields.
Frequently Asked Questions
You can build complex types by intersecting two or more types. For example,
type Name = { name: string };
type Age = { age: number };
type Address = { city: string };
type FullPerson = Name & Age & Address;
const person: FullPerson = {
name: "Daniel",
age: 25,
city: "New York"
};
In this example, FullPerson
is an intersection of Name
, Age
, and Address
. So, person
must include all three properties: name
, age
, and city
.
Also Read: