TS基础篇4:解构 与 展开

(一)解构数组

1、解构赋值

let input = [1, 2];
let [first, second] = input;

//相当于使用了索引
let first = input[0];
let second = input[1];

2、作用于函数参数

function f([first, second]: [number, number]) {
    console.log(first);
    console.log(second);
}
f(input);

3、...语法创建剩余变量

var testFun = function () {
    let [first, ...rest] = [1, 2, 3, 4];
    console.log(first);
    console.log(rest);
};
testFun();
输出:
1
[2, 3, 4]

~~由于是JavaScript, 你可以忽略你不关心的尾随元素或其它元素

let [first] = [1, 2, 3, 4];
console.log(first);      // 1
let [, second, , fourth] = [1, 2, 3, 4];   // 2  4

(二)解构对象

1、解构赋值
let o = {
    a: "foo",
    b: 12,
    c: "bar"
};
let { a, b } = o;

2、指定类型

let {a, b}: {a: string, b?: number} = o;
?:代表可选属性

3、使用 ...语法

let { a, ...passthrough } = o;
let total = passthrough.b + passthrough.c.length;

4、属性重命名

let { a: newName1, b: newName2 } = o;

5、函数声明

type C = { a: string, b: number }
function f({ a, b }: C): void {
    // ...
}


(三)展开数组

let first = [1, 2];
let second = [3, 4];
let bothPlus = [0, ...first, ...second, 5];

bothPlus的值为[0, 1, 2, 3, 4, 5]。 展开操作创建了 first和second的一份浅拷贝。

(四)展开对象

let defaults = { food: "spicy", price: "$$", ambiance: "noisy" };
let search = { ...defaults, food: "rich" };

search的值为{ food: "rich", price: "$$", ambiance: "noisy" }.
注意:展开是从左至右进行处理,但结果仍为对象。 这就意味着出现在展开对象后面的属性会覆盖前面的属性。

注意:对象展开还有其它一些意想不到的限制。

大体上是说当你展开一个对象实例时,你会丢失其方法。

class C {
  p = 12;
  m() {
  }
}
let c = new C();
let clone = { ...c };
clone.p; // ok
clone.m(); // error!
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容