Destructuring in declarations and assignments

TypeScript 1.5 adds support to ES6 destructuring declarations and assignments.

Declarations

A destructuring declaration introduces one or more named variables and initializes them with values extracted from properties of an object or elements of an array.

For example, the following sample declares variables x, y, and z, and initializes them to getSomeObject().x, getSomeObject().y and getSomeObject().z respectively:

  1. var { x, y, z} = getSomeObject();

Destructuring declarations also works for extracting values from arrays:

  1. var [x, y, z = 10] = getSomeArray();

Similarly, destructuring can be used in function parameter declarations:

  1. function drawText({ text = "", location: [x, y] = [0, 0], bold = false }) {
  2. // Draw text
  3. }
  4. // Call drawText with an object literal
  5. var item = { text: "someText", location: [1,2,3], style: "italics" };
  6. drawText(item);

Assignments

Destructuring patterns can also be used in regular assignment expressions. For instance, swapping two variables can be written as a single destructuring assignment:

  1. var x = 1;
  2. var y = 2;
  3. [x, y] = [y, x];