Beginner's TypeScript #7

nhannguyendevjs

Nhan Nguyen

Posted on December 24, 2023

Beginner's TypeScript #7

Image description

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;
}
Enter fullscreen mode Exit fullscreen mode

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",
    },
  ],
}
Enter fullscreen mode Exit fullscreen mode

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[];
Enter fullscreen mode Exit fullscreen mode

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'
  }
]
Enter fullscreen mode Exit fullscreen mode

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

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:

💖 💪 🙅 🚩
nhannguyendevjs
Nhan Nguyen

Posted on December 24, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Beginner's TypeScript #tips
programming Beginner's TypeScript #tips

January 24, 2024

Beginner's TypeScript #27
programming Beginner's TypeScript #27

January 19, 2024

Beginner's TypeScript #26
programming Beginner's TypeScript #26

January 18, 2024

Beginner's TypeScript #25
programming Beginner's TypeScript #25

January 17, 2024