Beginner's TypeScript Section 18 exercises

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

Loading solution


0:00 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.

0:19 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.

0:39 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.

0:58 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.