Introduction
Typescript has many advanced typed capabilities which facilitate in writing dynamic code. There are multiple advanced Typescripts types: union, intersection, nullable, type aliases, and many more. In this blog, we will understand intersection type in Typescript.
Intersection type in Typescript
An intersection type creates a new type by combining all the existing types. This new type has all the features of the existing type. It is denoted by the ‘&’ symbol.
typeC = typeA & typeB
The typeC will have the properties of both typeA and typeB.
Let us understand the intersection type by the following examples
Example 1:
interface species {
type: string;
}
interface Animal {
description: string;
age: number;
}
interface Mammal {
firstName: string;
lastName: string;
}
let human: Mammal & Animal & species = {
type: 'human',
firstName: 'Jesus',
lastName: 'Christ',
age: 20,
description: 'Served Mankind'
}
Output:
In the above example, the human variable has all the species, Animal, and mammal properties. Each property of the object has a defined interface. Note that the structure of each property should match one another, else it will generate a compilation error.
Example 2:
interface species {
type: string;
}
interface Animal {
description: string;
age: string;
}
interface Mammal {
firstName: string;
lastName: string;
age: number;
}
let human: Mammal & Animal & species = {
type: 'human',
firstName: 'Jesus',
lastName: 'Christ',
age: 20,
description: 'Served Mankind'
}
console.log(human);
Output:
The above code generates a compilation error. This is because two different types cannot have the same member name. Here, Animal and Mammal types have defined the ‘age’ as one of their members. In such a situation, Typescript automatically assigns ‘never’ type to these members when they are combined in the intersection, which means that we can’t assign any value to these members in the intersection.
Therefore, if we want to create the intersection type from the given types, we must ensure that no one has the same member names.
Example 3:
interface X { x: boolean; }
interface Y { y: string; }
interface Z { z: number; }
interface A { a: X; }
interface B { a: Y; }
interface C { a: Z; }
type ABC = A & B & C;
let abc: ABC = {
a: {
x: true,
y: 'CodingNinjas',
z: 3000
}
};
console.log('abc:', abc);
Output:
Points to remember
- (A & B) & C is equivalent to A & (B &C).
- When we combine two types in an intersection, the order in which they are intersected doesn’t affect the output.
Example:
typeC = typeA & typeB
typeC = typeB & typeA
They both represent the same output.
Difference between Union and Intersection in Typescript
