⭐ Working with Arrays ⭐
We will look at a bit more complex type declarations.
We have a User interface and a Post interface:
interface User {
id: number;
firstName: string;
lastName: string;
role: "admin" | "user" | "super-admin";
posts: Post;
}
interface Post {
id: number;
title: string;
}
I created a defaultUser that has a couple of posts added:
export const defaultUser: User = {
id: 1,
firstName: "Matt",
lastName: "Pocock",
role: "admin",
posts: [
{
id: 1,
title: "How I eat so much cheese",
},
{
id: 2,
title: "Why I don't eat more vegetables",
},
],
}
But there is an error. The problem is that in the User interface, it is expecting a single Post instead of the array that defaultUser has.
We will determine how to fix this type of error by determining how to represent arrays.
👉 Solution:
There are two solutions to this problem.
➖ Add Square Brackets:
The first solution is to add a couple of square brackets to Post:
// Inside the User interface
posts: Post[];
Now if we create a posts consists of the type Post[], we will get autocomplete when we populate the id and title properties:
const posts: Post[] = [
{
id: 1,
title: 'autocomplete works'
}
]
➖ Use a Generic Type:
The second solution is to use a generic type.
This syntax uses the name of what we want (Array, in this case) followed by angle brackets with the type that will be in the array:
// Inside the User interface
posts: Array<Post>
The generic types are built into TypeScript without us having to import anything.
We will see more of them later when we get into Promises, Maps, and other more advanced types.
❓ Which one should you use ❓
Both options resolve to the same thing. It is just two different ways of writing it.
I like Post[] for arrays, but I wanted to show the generic type syntax since it comes up later.
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)