Typescript Intersection types

Intersection types allow us to combine two or more types into one. The resulting type will have all the properties of all the types. This allows us to get a Single type from existing types that has all the properties of both the types

Using intersection types

We can create intersection type using the following syntax. Each type is separated by & sign.

let a : type1 & type2 & .. & .. & typeN

Example

The following code creates the intersection type student from the Person & Employee type. 

Note that student has all the properties from the both the types. If you leave out of any one of the property as in name in the following code, the compiler will throw an error.

Common Primitive Property

It is allowed to have primitive property with same name & type as in the case of age in the example.

But if they differ in type, then resulting property will have the type never and you won’t be able to create the intersection until you fix the problem.

Common Non-Primitive Property

If you have a common non primitive property, then the typescripts creates an intersection of them also.

For Example, we have address property in both in Person & Student type. But they have different types ( HomeAddress & OfficeAddress). When we create interestsection of the Person & Student, the address becomes intersection of HomeAddress & OfficeAddress.

References

  1. Advanced Types

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top