Two Syntaxes for Arrays
There are two different syntaxes for defining arrays in TypeScript.
The Array Modifier Syntax []
The first way to specify an array is to use square brackets added to the end of the type.
For the ShoppingCart
example, defining an array of item
strings would looks like this:
Transcript
00:00 Okay, there are actually two different syntaxes for you to use here. The main one that we have here is items, and we're going to say, okay, it's not a string, it's actually an array of strings. So we add this array modifier to the end here. And this means then that we can't just pass one string, we have to pass multiple strings.
00:20 So item one is going to error here because it's not assignable to array string here. And this is a nice syntax, it's a lovely first class way of representing arrays of strings here. There is an alternative, and the alternative is to do this.
00:36 We have items, and let's say array, and these two sort of like angle brackets, and you pass a string to it. Now, this syntax is kind of more explicit, really, it shows like array is kind of like a type function here, and we're passing string to it. We can pass a number to it if we want to as well.
00:56 But this syntax, you're going to see this kind of a lot as well. And there's an open debate in the TypeScript community as to which one is better. I'll link to an article below where I dive into exactly all of the differences. I think this syntax is really useful to know, because this is going to come up later as well when we look at like promises or records or things like that.
01:15 So this type of syntax with the angle brackets is very, very common in TypeScript. But given that we have this beautiful sort of like angle bracket syntax, I kind of like using this. And this is what the TypeScript error messages say as well.
01:29 So if you're reading something in TypeScript, you're most often going to see it represented like this with the angle brackets, or sorry, the square brackets at the end, rather than with the angle bracket syntax here. So because of that, I tend to prefer the square bracket syntax.