⭐ 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",
},
],
};
};
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[] } => {
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} => {
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.
I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
Top comments (0)