Post

Intersection types in TypeScript

Intersection types

Purpose of this post is to get a basic understanding of intersection types and realize pros and cons of intersection types.

Last time we talked about union types:

let x: string | number;

Variable x can be either string or a number. Consequently, you can use type guarding technique to exclude one of the types.

TypeScript also lets you define intersection types:

type PQ = P & Q;

let x: PQ;

Therefore, variable x has all properties from both P and Q.

Don’t let the intersection term lead you in wrong direction and confuse the logic with sets in mathematics.

In TypeScript if one type is intersection of two other types consequently that type will have all properties from two intersected types:

https://gist.github.com/Ibro/262ee343ea3a2a244ec76b44f6723713

Be careful when mixing types that share some of the property names that don’t have same type:

https://gist.github.com/Ibro/f07738923d40753ec7a30449adeb5f79

You will notice that type X and type Y both have property c. However, type of the property is not the same and once we try to assign value to it we get an error from the compiler.

We can combine non primitive property types with the same property name:

https://gist.github.com/Ibro/74c8af70d5b2367e86068209e90aa778

As you can see we got interfaces A, B, C and all have same property name - x. However, type of the property x is different for those interfaces ( A, B, C ).

https://gist.github.com/Ibro/2afef19a11adde5db14ac21d75280be1

As a result we can combine those types to form a new type and use it:

let abc: ABC = { x: { d: true', e: 'codingblast', f: 3 } };

Do notice that we have 3 different properties on property x of object abc:

Type Relationships

It is important to notice that when you intersect types order does not matter:

type XY = X & Y; type YX = Y & X;

Both,XY and YX have the same properties and are almost equal.

Also, (X & Y) & Z is equivalent to**X & (Y & Z)**.