DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Beginner's TypeScript #15

Combining Types to Create New Types

Continuing with User and Post, we now have a getDefaultUserAndPosts function that has an unknown return type:

export const getDefaultUserAndPosts = (): unknown => {
  return {
    id: "1",
    firstName: "Uri",
    lastName: "Nguyen",
    posts: [
      {
        id: "1",
        title: "How I eat so much cheese",
        body: "It's pretty edam difficult",
      },
    ],
  };
};
Enter fullscreen mode Exit fullscreen mode

We will figure out how to update the return type for the function so that it is both User and { posts: Post[] }.

🌟 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[] } => {
Enter fullscreen mode Exit fullscreen mode

It says that we want to return a User and 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 is 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} => {
Enter fullscreen mode Exit fullscreen mode

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 => {
Enter fullscreen mode Exit fullscreen mode

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.


I hope you found it useful. Thanks for reading. 🙏

Let's get connected! You can find me on:

Top comments (0)