What are intersection types in Typescript ?
In Typescript, Although intersection and union types are similar, they are employed in completely different ways. An intersection type is a type that merges several kinds into one. This allows you to combine many types to create a single type with all of the properties that you require. An object of this type will have members from all of the types given. The ‘&’ operator is used to create the intersection type.
Example 1: Creating an intersected type: In this example, two interfaces named student and teacher are created. Intersected type is created by using ‘&’ between student and teacher. Intersected type contains all the properties of the two interfaces. An obj of intersection type is created and values are retrieved from it. We can not use a property without assigning it to the intersection type object.
Example 2: In this example, we create two interfaces A and B, in which there are two properties named ‘feauA’ and ‘feauB’. But the type of feauA isn’t the same in both the interfaces, when we try to assign a value 20 to feauA typescript compiler raises an error as the intersection type is of the type ‘string & number’. If we try to assign a string to feauA, the error is not raised as to when intersected the type is String.
error TS2322: Type 'number' is not assignable to type 'never'. obj1.feauA = 20; // Error, Type '20' is not assignable // to type 'string & number'
Example 3: Intersection types are commutative and associative: The order of the intersection doesn’t matter when we intersect two or more types. Even if the order of intersection changes the type of the intersected objects are the same, the ‘typeof’ operator is used to check that, the properties of the intersected objects are also the same.
commutative property: A&B = B&A associative property: (A&B)&C = A&(B&C)
height length false true true