TypeScript supports the following forms of Destructuring (literally named after de-structuring i.e. breaking up the structure):
- Object Destructuring
- Array Destructuring
Destructuring is useful because it allows you to do in a single line, what would otherwise require multiple lines. Consider the following case:
Here in the absence of destructuring you would have to pick off one by one from .
To assign an extracted variable to a new variable name you can do the following:
Additionally you can get deep data out of a structure using destructuring. This is shown in the following example:
Object Destructuring with rest
You can pick up any number of elements from the an object and get an object of the remaining elements using object destructuring with rest.
A common use case is also to ignore certain properties. For example:
A common programming question: "How to swap two variables without using a third one?". The TypeScript solution:
Note that array destructuring is effectively the compiler doing the and so on for you. There is no guarantee that these values will exist.
Array Destructuring with rest
You can pick up any number of elements from the array and get an array of the remaining elements using array destructuring with rest.
Array Destructuring with ignores
You can ignore any index by simply leaving its location empty i.e. in the left hand side of the assignment. For example:
Destructuring can make your code more readable and maintainable by reducing the line count and making the intent clear. Array destructuring can allow you to use arrays as though they were tuples.
ТРАНСТЕКСТ работал на полную мощность. Расход энергии даже чуть выше обычного: более полумиллиона киловатт-часов с полуночи вчерашнего дня. - И что все это. - Не знаю.