Typescript Deep Dive by Basarat Ali Syed
Typescript Deep Dive by Basarat Ali Syed
Typescript Deep Dive by Basarat Ali Syed
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
TypeScript <strong>Deep</strong> <strong>Dive</strong><br />
Destructuring<br />
TypeScript supports the following forms of Destructuring (literally named after de-stucturing i.e. breaking up the structure):<br />
1. Object Destructuring<br />
2. Array Destructuring<br />
It is easy to think of destructuring as an inverse of structuring. The method of structuring in JavaScript is the object literal:<br />
var foo = {<br />
bar: {<br />
bas: 123<br />
}<br />
};<br />
Without the awesome structuring support built into JavaScript creating new objects on the fly would indeed be very<br />
cumbersome. Destructuring brings the same level of convenience to getting data out of a structure.<br />
Object Destructuring<br />
Destructuring is useful because it allows you to do in a single line, what would otherwise require multiple lines. Consider the<br />
following case:<br />
var rect = { x: 0, y: 10, width: 15, height: 20 };<br />
// Destructuring assignment<br />
var {x, y, width, height} = rect;<br />
console.log(x, y, width, height); // 0,10,15,20<br />
Here in the absence of destructuring you would have to pick off x,y,width,height one <strong>by</strong> one from rect .<br />
Additionally you can get deep data out of a structure using destructuring. This is shown in the following example:<br />
var foo = { bar: { bas: 123 } };<br />
var {bar: {bas}} = foo; // Effectively `var bas = foo.bar.bas;`<br />
Array Destructuring<br />
A common programming question : Swap two variables without using a third one. The TypeScript solution:<br />
var x = 1, y = 2;<br />
[x, y] = [y, x];<br />
console.log(x, y); // 2,1<br />
Note that array destructuring is effectively the compiler doing the [0], [1], ... and so on for you. There is no guarantee<br />
that these values will exist.<br />
Array Destructuring with rest<br />
You can pick up any number of elements from the array and get an array of the remaining elements using array<br />
destructuring with rest.<br />
Destructuring<br />
26