Two Ways to Represent Arrays
There are two solutions to this problem.
Add Square Brackets
The first solution is to add a couple of square brackets to
Now if we create a
posts consts of the type
Post, we'll get autocomplete when we populate the
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:
The generic types are built into TypeScript without us having to import anything.
We'll be seeing 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's just two different ways of writing it.
Post for arrays, but I wanted to show the generic type syntax since it comes up later.
There are two solutions to this problem. The first one is to add a couple of square brackets just at the end of Post here. That turns it into an array of posts. I can extract this into a type itself. I can say const posts is Post array. Now, we get to specify all the array of posts, and I get my stuff all autocompleted for me, which is really, really nice. That's the first type of syntax you can use.
There's a second type of syntax which specifies that using...This is what's called a generic type. This array type here is something I don't have to import from anywhere. It's just inside the language. If I misspell it, then I'm going to get an error there, obviously, but array just is available globally.
What I do here is I pass it the thing that I want to put in the array. It's an array of posts. This little square...Not square brackets. I can't remember the name for them, but these little braces here, whatever they're called, this syntax is very, very common in especially more advanced types. I want to point this out.
It's up to you which one you use. They resolve into exactly the same thing. It's just two different ways of expressing the same thing. I like this one, but then I wanted to teach this one because it comes up a lot later, especially with promises, especially with maps, sets, records, things like that. Do get used to this syntax. That's the main way to express arrays in TypeScript.