Nested Destructuring#

Nested Destructuring#

It's common for objects to contain nested objects and arrays. Destructuring allows us to extract properties that are nested in objects using the syntax that we learned above for destructuring arrays and objects.

In the example below, we declare a laptops variable that contains nested arrays and objects:

If we want to extract the second zip code of the first laptop, we would do the following:

Breaking it down, we see that we first deconstruct the array using square bracket to get the first item in the array. From the first item, we deconstruct the sellerZipCodes property, which we then deconstruct the secondZipCode from. Notice the empty comma to ensure that we skip over the first element in the array.

It's important to keep in mind that destructuring is not a safe operation, meaning that nested property that do not exist at runtime will throw an error:

 

This page is a preview of Beginners Guide to TypeScript

No discussions yet