In this lecture, we're going to look at how to apply types to an object working with objects, and
TypeScript is interesting.
We can add optional properties, interfaces and work with nested structures.
Let's take it one step at a time.
Below the array, we will add an object called accounts.
The accounts object will represent a bank accounts.
Will keep it simple by adding two properties called name and balance.
The name property has a string value, the balanced property has a number of value.
We haven't annotated the object.
Luckily, type inference kicks in since we're initializing the object with some values.
If we hover our mouse over the object, TypeScript will correctly infer the types of our properties.
It's also possible to explicitly define the type for an object after the variable name.
Let's add a colon, followed by a pair of square brackets.
The syntax for annotating an object is similar to creating an object itself.
The annotation should be an object with a list of properties that can be found within the object.
If we decide to annotate properties in our object explicitly, we must set a type for every property.
If there's a property inside our object that's not annotated, TypeScript will throw an error.
Inside this object, we'll add the name and balance properties.
They will be set to string and no, respectively.
In some scenarios, you may want to make a property optional.
For example, let's say we had a property called status.
The type for this property will be set to string.
After adding this type, an error is thrown by TypeScript taking a closer look at the error.
It's telling us the status type is missing from the object.
It's possible we may want to add this property at a later point in our application.
We can get around this error without adding the property in our object by making it optional in the
annotation object.
We will add a question mark symbol after the status property.
We're adding this symbol to the annotation.
It's not being applied to the value itself.
It can be confusing with the syntax, since the annotation and value are formatted the same.
After adding the symbol, the error has disappeared.
Great.
Before I end this lecture, there's one more thing I want to mention.
It's not uncommon to have to combine arrays and objects.
For example, instead of a single account, we may need to work with multiple accounts below this variable.
We will declare another variable called accounts.
For the sake of simplicity, it won't have a value.
We will annotate this variable by adding curly braces, followed by a pair of square brackets.
This syntax will tell TypeScript the variable will store an array of objects.
That's all there is to it in the next lecture.
We will look at how we can clean this up by using interfaces.