If you already have a subscription, you can sign in.
Enjoy free content straight from your inbox 💌
00:00
Here we have a type representing a point in two dimensional space with members X and Y of type number. Now within our library, we also want to express points in three dimensional space, and we have the members x, y, and Z of type number. Notice the duplication between the members X and Y of 0.2 D and 0.3 D within the same code base. Now you might be familiar with the concept of class inheritance intersection types behave in a similar way and allow you to combine the features of any two given types.
00:33
So we can remove the duplication of the X and Y members in the 0.3 D type and simply use a type intersection with the 0.2 D. By using the amp percent operator. Here we are saying that 0.3 D has all the members of 0.2 D and the member Z of type number. Now of course, we can change multiple types with multiple amp percent signs, and additionally we can use intersection types in line. Let's look at another example here. We have three types. A type person with a member name of type string,
01:06
a type email with a member email of type string, and a type phone with a member phone of type string. We have this utility function that uses the name, the email, and the phone to contact an individual. Now we can enforce that the contact function is called with all the correct details by using an intersection type, combining the members of person email and phone. And now we get to invoke the contact function with complete compile time type safety. And if there are any type errors, for example, a missing member, we get a nice compiler
01:39
error from TypeScript. Now, one final thing worth mentioning is just like type unions, we can extract an intersection type into a type alias, and we previously saw this usage in 0.3 D as well. Similarly, we can add a leading M percent before a type intersection and it has no impact on the semantics of the type and is there purely for readability purposes.