解构赋值

数组解构

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

上面的写法等价于:

  1. first = input[0];
  2. second = input[1];

利用解构赋值交换变量:

  1. [first, second] = [second, first];

函数参数解构:

  1. function f ([first, second]: [number, number]) [
  2. console.log(first)
  3. console.log(second)
  4. ]
  5. f(1, 2)

解构剩余参数:

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

也可以忽略其它参数:

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

或者跳过解构:

  1. let [, second, , fourth] = [1, 2, 3, 4]

对象解构

示例一:

  1. let o = {
  2. a: "foo",
  3. b: 12,
  4. c: "bar"
  5. };
  6. let { a, b } = o;

就像数组解构,你可以用没有声明的赋值:

  1. let a: number,
  2. b: number;
  3. ({a, b} = {a: 123, b: 456})
  4. console.log(a, b) // 123 456

你可以在对象里使用 ... 语法创建剩余变量:

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

属性解构重命名

你也可以给属性以不同的名字:

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

注意,这里的冒号不是指示类型的。 如果你想指定它的类型, 仍然需要在其后写上完整的模式。

  1. let {a, b}: {a: string, b: number} = o;

默认值

  1. function keepWholeObject(wholeObject: { a: string, b?: number }) {
  2. let { a, b = 1001 } = wholeObject;
  3. }

展开操作符

  • 展开数组
  • 展开对象
    • 不会展开方法

解构赋值用于函数声明

  1. type C = {a: string, b?: number}
  2. function f ({a, b}: C): void {
  3. // ...
  4. }

解构赋值用于加载指定模块成员