In this lecture, we're going to learn how to annotate arrays and objects.
Up until now, we've been focused on primitive types and functions.
It's time to shift our focus to more complex types.
The syntax for annotating arrays and objects is similar to annotating anything else in TypeScript.
In our file, let's add a section for this demonstration.
We will create an array called items with some string values.
If we define an array with some values, TypeScript will infer the type of our array, according to
our editor, TypeScript is inferring the array will store strings.
That's great.
But what if we want it to initialize an empty array?
If our array were empty, type inference wouldn't work by removing the items in the array, the type
of the array has been set to any.
In that case, we can explicitly annotate the array like we would any other variable after the name
of the variable will add a colon, followed by the type of values the array will store.
Finally, we'll set the type two string.
Despite setting the type.
We'll get an error, the error will tell us the value is invalid.
The problem is how we've annotated the variable.
There's one extra bit of code we need to add after the type.
We'll add a pair of square brackets by adding the square brackets.
TypeScript will assume the array will be filled with strings.
We can take this a step further by adding union types if we need to store an array of different types
of values.
We can add a union type.
We will add on to the annotation by including the number type.
There's one important note I want to add these square brackets are being added to both types.
If we didn't include the square brackets to the number of type, TypeScript would not allow us to store
an array of numbers.
Instead, it'll think the variable can hold an array of strings or a single number.
Therefore, these square brackets must be applied to both types.
One last thing TypeScript can infer union types.
For example, we can get the same union type if the array is filled with strings and numbers.
So let's remove the annotation.
Next, let's add a number and string to the array.
The array stores two types if we hover our mouse over the variable, the editor will tell us we have
a union type that's very convenient.
We don't have to worry about TypeScript accidentally adding the any type which we should avoid.
Let's move on to objects in the following lecture.