Table of contents
1.
Introduction
2.
Intersection type in Typescript
2.1.
Points to remember
3.
Difference between Union and Intersection in Typescript
4.
Frequently Asked Questions
5.
Key Takeaways
Last Updated: Mar 27, 2024

Intersections in Typescript

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

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

Frequently Asked Questions

Q1: What is an unknown type, and when to use it in Typescript?

Ans: The unknown type is the type-safe counterpart of any type. We can assign anything to the unknown type, but it isn’t assignable to anything but itself. We cannot perform any operations on a variable of an unknown type without first asserting or narrowing it to a more specific type.

Consider the following example: 

let f: unknown = "Coding Ninjas";
let bar: string = f;

 

Output:

We create the f variable of unknown type and assign a string value to it. If we set that unknown variable to a string variable bar, the compiler gives an error.

 

Q2: What is the typeof operator? How is it used in Typescript?

Ans: Type typeof operator in Typescript returns the type of operand as the string.

Example:

console.log(typeof 10); 
console.log(typeof 'codingNinjas'); 
console.log(typeof false); 

 

Output:

 

Q3: What are triple-slash directives?

Ans: Triple-slash directives are single-line comments that contain a single XML tag. Typescript uses this XML tag as a compiler directive. Triple-slash directives must be placed at the top of the containing file else Typescript treats them as regular comments if placed in the code block. Only single or multi-line comments can come before the triple-slash directive.

The primary objective of the triple-slash directive is to include other files in the compilation process. They also order the output when using --out or --outFile. The output files are produced to the output file location in the same order as the input files.

Key Takeaways

An intersection type lets us combine multiple types into one type. The new type formed after the intersection will have the properties of all its parent types. The types order is not important while we combine them.

If you are a beginner interested in learning and exploring other fields, you can follow our guided path to understand the core subjects of computers and get a good grip on DSA concepts. 

Live masterclass