Typescript - 将函数参数解构为数组

Typescript - Destucturing function parameter to array

为什么这段代码会产生错误?

let promises = [p1(), p2(), p3()];
$q.all(promises)
  .then(([p1Result, p2Result, p3Result]) => {
    // ...
  });

但是当我把它变成这个时,它起作用了:

let promises = [p1(), p2(), p3()];
$q.all(promises)
  .then(results => {
    let [p1Result, p2Result, p3Result] = results;
    // ...
  });

我遇到的另一个问题是我无法为 p1Resultp2Resultp3Result 定义类型。更不用说 Typescript 编译器不会推断它们的类型。

它们的工作原理相同

TypeScript

declare var $q: any;
declare var p1: any;
declare var p2: any;
declare var p3: any;
let promises = [p1(), p2(), p3()];


$q.all(promises)
  .then(([p1Result, p2Result, p3Result]) => {
    // ...
  });

$q.all(promises)
  .then(results => {
    let [p1Result, p2Result, p3Result] = results;
    // ...
  });

生成JavaScript:

var promises = [p1(), p2(), p3()];
$q.all(promises)
    .then(function (_a) {
    var p1Result = _a[0], p2Result = _a[1], p3Result = _a[2];
    // ...
});
$q.all(promises)
    .then(function (results) {
    var p1Result = results[0], p2Result = results[1], p3Result = results[2];
    // ...
});

你可以see that TypeScript is happy with both code samples