Skip to content

Wrong emit for destructuring assignment #19020

Closed

Description

TypeScript Version: 2.5.3

Code

let foo: any = { foo: 1, bar: 2 };
let bar;
({ foo, bar } = foo);
console.log(foo, bar);

http://www.typescriptlang.org/play/#src=let%20foo%3A%20any%20%3D%20%7B%20foo%3A%201%2C%20bar%3A%202%20%7D%3B%0D%0Alet%20bar%3B%0D%0A(%7B%20foo%2C%20bar%20%7D%20%3D%20foo)%3B%0D%0Aconsole.log(foo%2C%20bar)%3B

Expected behavior:
Output: 1, 2
Untranspiled code works as expected for example in latest Chrome.

Actual behavior:
Output: 1, undefined

The destructuring is transpiled to (foo = foo.foo, bar = foo.bar);. After assigning foo the access of foo.bar yields undefined.
In such cases (possibly in all cases) there is the need for an intermediate variable that stores the destructured object (or array).

Activity

  1. geirsagberg commented on Dec 11, 2017

    @geirsagberg

    Had this same issue today when converting a project from Babel to TypeScript, In Babel it works as expected, but TypeScript (2.6.2) has the bug mentioned above.

    Babel produces this:

    "use strict";
    
    var foo = { foo: 1, bar: 2 };
    var bar = void 0;
    var _foo = foo;
    foo = _foo.foo;
    bar = _foo.bar;
    
    console.log(foo, bar);

    However, if changing the code to:

    let x = { foo: 1, bar: 2 };
    let bar;
    ({ foo, bar } = x);
    console.log(foo, bar);

    Then babel produces:

    "use strict";
    
    var x = { foo: 1, bar: 2 };
    var bar = void 0;
    foo = x.foo;
    bar = x.bar;
    
    console.log(foo, bar);

    So it is obvious some kind of detection is being done here, and TypeScript should do this as well.

  2. added
    Fixed
    on Jan 17, 2018
  3. locked and limited conversation to collaborators on Jul 3, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

BugFixed

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions