Intersection types
Last updated
Last updated
Just as allow us to combine multiple types by using the |
operator, so do intersection types via the &
operator. An intersection between two or more types means that the transpiler is expecting the combined properties of all of the types being intersected. Say we want to create an authenticated user using the information found in a variable typed User
and one typed AuthToken
. Let's start with two interfaces defining the two types:
Now let's create two variables of those types:
Finally, let's create a function that takes these vars as its arguments and whose return value is an intersection of the two types:
Note how we use the &
in the return portion of the function's definition to tell TypeScript that we want the returned value to be an intersection of both User
and AuthToken
.
If we need to reuse this intersection in different places, we can save a bit of typing by assigning it to a named type like so:
And then using the newly created type instead of manually writing the intersection out: