TypeScript:解构和展开

一、解构

解构数组

1、解构赋值

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

2、作用于函数参数

function f([first, second]: 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!

posted on 2024-03-25 11:38  梁飞宇  阅读(196)  评论(0)    收藏  举报