TypeScript入门教程 之 解构
TypeScript支持以下形式的解构(以解构的名义命名,即分解结构):
- 对象分解
- 阵列解构
人们很容易将解构视为结构的逆。JavaScript中的结构化方法是对象文字:
var foo = { bar: { bas: 123 } };
如果没有JavaScript内置的强大结构支持,那么即时创建新对象确实非常麻烦。解构为从结构中获取数据带来了相同程度的便利。
对象分解
销毁非常有用,因为它允许您在一行中执行操作,否则将需要多个行。考虑以下情况:
var rect = { x: 0, y: 10, width: 15, height: 20 }; // Destructuring assignment var {x, y, width, height} = rect; console.log(x, y, width, height); // 0,10,15,20 rect.x = 10; ({x, y, width, height} = rect); // assign to existing variables using outer parentheses console.log(x, y, width, height); // 10,10,15,20
在这里,在没有破坏的情况下,您将必须从中x,y,width,height
一一挑选rect
。
要将提取的变量分配给新的变量名称,可以执行以下操作:
// structure const obj = {"some property": "some value"}; // destructure const {"some property": someProperty} = obj; console.log(someProperty === "some value"); // true
另外,您可以使用解构从结构中获取深层数据。在以下示例中显示:
var foo = { bar: { bas: 123 } }; var {bar: {bas}} = foo; // Effectively `var bas = foo.bar.bas;`
进行对象分解
您可以从对象中拾取任意数量的元素,然后使用对象结构化其余部分来获取其余元素的对象。
var {w, x, ...remaining} = {w: 1, x: 2, y: 3, z: 4}; console.log(w, x, remaining); // 1, 2, {y:3,z:4}
一个常见的用例也是忽略某些属性。例如:
// Example function function goto(point2D: {x: number, y: number}) { // Imagine some code that might break // if you pass in an object // with more items than desired } // Some point you get from somewhere const point3D = {x: 1, y: 2, z: 3}; /** A nifty use of rest to remove extra properties */ const { z, ...point2D } = point3D; goto(point2D);
阵列解构
一个常见的编程问题:“如何在不使用第三个变量的情况下交换两个变量?”。TypeScript解决方案:
var x = 1, y = 2; [x, y] = [y, x]; console.log(x, y); // 2,1
请注意,数组解构实际上是编译器[0], [1], ...
为您执行的操作,等等。无法保证这些值将存在。
进行阵列解构
你可以拿起任何数量从数组中的元素,并得到一个数组使用数组解构与其他剩余的元素。
var [x, y, ...remaining] = [1, 2, 3, 4]; console.log(x, y, remaining); // 1, 2, [3,4]
带忽略的数组解构
您可以忽略任何索引,只需将其位置保留为空即可,即, ,
在分配的左侧。例如:
var [x, , ...remaining] = [1, 2, 3, 4]; console.log(x, remaining); // 1, [3,4]
生成的JS
非ES6目标的JavaScript生成仅涉及创建临时变量,就像您在没有本地语言支持进行解构时必须自己做一样,例如
var x = 1, y = 2; [x, y] = [y, x]; console.log(x, y); // 2,1 // becomes // var x = 1, y = 2; _a = [y,x], x = _a[0], y = _a[1]; console.log(x, y); var _a;
摘要
通过减少行数并弄清楚意图,解构可以使您的代码更具可读性和可维护性。数组解构可以使您像使用数组一样使用数组。
翻译来源:https://gitee.com/yunwisdoms/typescript-book/blob/master/docs/destructuring.md