Typing Arrays and Tuples0:00
So we've already seen how to do basic type declarations for strings, numbers, we've seen interfaces for object types, but how do we type collections of data like arrays and tuples? Type declarations for these are very simple and easy to understand. So let's pretend we have an array of the Laracast team. In order to add a type to this, we just use a colon syntax followed by the type. So we have a string array, and that is how you type arrays, you type the type of what's in the array, and then just some square brackets to say we have an array of type string. List of numbers, the exact same thing, we have a colon, and then we have a number this time followed by the square bracket syntax to say it's an array of numbers. Now I will just show you another way of doing an array syntax, which is from the early days.
Using Union Types in Arrays1:53
So we simply just use this symbol here, this pipe symbol to say, or, and we're basically saying this is a string or a number. But the thing is, we need to add some brackets around here to say the array is of string or numbers. So we see that gets rid of this error. And so let me just pull up this error message again, so you can walk through it. We basically have type string or number array, which is what is on the right-hand side here. So TypeScript can already infer the type of this because it's got good type inference, is not assignable to type string or number array. So that is what we have on the left here.
Comparing Arrays vs Tuples3:31
So if we try and copy and paste this type definition straight below where we've reversed the order, we can see that these are clearly different. So an array of strings or numbers is very different from a tuple of number and string. And if we inspect this message, it says type string is not assignable to type number. And that is because we have said the first element in this array is of number type and the second one is a string. And that's why we get this second error message here saying that type number is not assignable to string. So we need to reverse these types here. Making the first entry string gets rid of the first error and making the second one
Fixing Tuple Type Order4:06
So we need to reverse these types here. Making the first entry string gets rid of the first error and making the second one gets rid of the second one. And that's really all there is to array types and tuple types. We simply define what is inside the array first and then follow with this array syntax. But that is all there is to arrays and tuples.
