Intersection types in TypeScript
All posts in TypeScript series:
- TypeScript – Union types, type guards and type aliases
- Intersection types in TypeScript
- Tuples in TypeScript
- Decorators with 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:
Be careful when mixing types that share some of the property names that don’t have same type:
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:
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 ).
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)
.