Search code examples
typescriptdestructuring

Typescript - Destucturing function parameter to array


Why this code produce errors?

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

But when I turn it to this, it works:

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

Another problem I have is that I can't define a type for p1Result, p2Result, p3Result. Not to mention that Typescript compiler does not infer types of them.


Solution

  • They both work the same

    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;
        // ...
      });
    

    Generated 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];
        // ...
    });
    

    You can see that TypeScript is happy with both code samples