Intersection types allow us to combine other types.
Say, we have an interface for Person
:
interface Person {
name: string;
gender: string;
}
There is also an another interface for Farmer
:
interface Farmer {
crop: string;
}
Now, for some reasons we need a new interface that contains the properties of both Person
and Farmer
. One option is to list out all properties again as shown below:
interface PersonFarmer {
name: string;
gender: string;
crop: string;
}
Or, we can use intersection operator like below:
type PersonFarmer = Person & Farmer;
Note that we need to use type
when we use intersection operator. Instead of type
, if we need to use interface
for PersonFarmer
, then we can consider extending Person
and Farmer
.