3.12 Destructuring

The Mozilla developer networks defines destructuring as follows:

The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

Getting Ready

All you need to be able to use destructuring is an installation of TypeScript 2.0 or higher.

How to do it…

Let’s imagine that we have the following array:

const foo = ['one', 'two', 'three'];

And we need to access each item in the array as an independent variable:

const one   = foo[0];
const two   = foo[1];
const three = foo[2];

In that scenario we could use destructuring to avoid a lot of code duplication:

const [one, two, three] = foo;

How it works…

The TypeScript compiler generates the following code for the preceding code snippet:

const foo = ['one', 'two', 'three'];
const one = foo[0];
const two = foo[1];
const three = foo[2];
const one = foo[0], two = foo[1], three = foo[2];

There’s more…

Destructuring can also be applied to object literals:

const {a, b} = {a:1, b:2};

And used in combination with the spread operator:

const [a, b, ...rest] = [1, 2, 3, 4, 5];

Source Code


See also

Please refer to the recipe about <div class="important-text">rest parameters</div> and the <div class="important-text">spread operator</div> if you are unfamiliar with those terms.

Shiv Kushwaha