Beginner's TypeScript Tutorial (18 exercises)
solution

Combine Inline or at the Type Level

This syntax might look confusing, but it is exactly what we want:

export const getDefaultUserAndPosts = (): User & { posts: Post[] } => {

It says that we want to return a User as well as an array of Posts.

The & tells TypeScript that we want to intersect the two.

This is similar to what we saw with extends previously, but this time instead of inheriting, we are combining.

With extends you inherit, and with & you combine.

So we are making a single return type by combining User with an array of Posts.

It's possible to intersect multiple types, including those we create inline.

For example, we can also add an age:

export const getDefaultUserAndPosts = (): User & { posts: Post[] } & { age: number} => {

If the return type starts to get too messy, you can do the intersection at the type level:

type DefaultUserAndPosts = (): User & { posts: Post[] } & { age: number}

export const getDefaultUserAndPosts = (): DefaultUserAndPosts => {

Now when working with the DefaultUserAndPosts type, we would get autocompletion on all of the required properties.

Intersection is usually used for composing types from other types, but can be useful in other situations as well.

Transcript

The syntax down here might look a little bit confusing, but this is exactly what we want here. We want to say we want to return a user, and we want to return an array of posts. What this allows us to do is this little intersection symbol there means that we intersect the two.

This is very similar to what we saw last time with extends. Except, with extends, you inherit. With intersection, you combine. You make type that is a combination of user and these posts down here. If I remove one of these, then this is going to yell at me. It's saying, "Object blah-blah blah-blah," because ID doesn't exist on just posts.

We need to be able to say user and this, and we can do multiple of these if we want. We can say user and age is number, for instance, and age 123. We can even do this at the type level outside if this starts getting a little bit too ugly.

We can say that defaultUserAndPosts is a type, and type defaultUserAndPosts is this, which is really nice. This symbol there means you combine two types together to create a new type. What TypeScript does when you hover over it is it shows you all of the component parts that make up that intersection. This is really useful for lots of different situations, but usually for composing types from other types.