Compound Data Structures in TypeScript
Introduction
Welcome to our exploration of Compound Data Structures in TypeScript. Having navigated through Maps, Sets, and Arrays, we'll delve into Nested Maps and Nested Arrays. These structures enable us to handle complex and hierarchical data, which is typical in real-world scenarios. Nested data structures are commonly used to represent data models like organizational charts, product categories, and multi-dimensional datasets. This lesson will guide you through a recap of the basics, as well as the creation and modification of nested Maps and Arrays.
Recap: Maps, Arrays, and Understanding Nested Structures
As a quick recap, Arrays are mutable, ordered collections, while Maps are collections of key-value pairs with maintained insertion order. These structures can be nested. Here's a simple example of a school directory:
Creating Nested Maps and Arrays
Just like their non-nested versions, creating nested structures is straightforward, with added type safety in TypeScript.
Nested Map:
Nested Array:
Nested Maps and Arrays:
Accessing Values in Nested Structures
The retrieval of values from nested Maps or arrays is facilitated by TypeScript's type-checking, which ensures that operations are performed on valid structures.
From Nested Map:
In this code example, the optional chaining operator (?.) is used in nestedMap.get('fruit')?.get('apple') to avoid errors:
nestedMap.get('fruit')attempts to access the nestedMapassociated with the'fruit'key.- The
?.operator ensures that if'fruit'does not exist (i.e., returnsundefined), it does not attempt to call.get('apple'), which would cause an error. - Instead, the expression safely evaluates to
undefinedif'fruit'is missing, preventing a runtime error. - If
'fruit'is present, then.get('apple')executes normally, retrieving the color'red'.
From Nested Array:
From Both:
