Skip to content

Destructuring breaks program order #32305

Closed
@Validark

Description

@Validark

I was wondering in what order destructuring is supposed to execute expressions, so I wrote the following test. I tried it in Chrome's V8 and Node, and they both gave me the same answer. I tried it in ts-node/TS, and it gave me a different answer.

TypeScript Version: any

Search Terms: destructuring breaks program order

Code

function f() {
    console.log("f");
    return { x: 1 };
}
function g() {
    console.log("g");
    return "x" as "x";
}
const { [g()]: x } = f();

Expected behavior: f g

Actual behavior: g f

Playground Link: https://www.typescriptlang.org/play/?target=1#code/GYVwdgxgLglg9mABMAFASkQbwFCL4iBAZzgBsBTAOlLgHMUAiYBtAbl3wCdyoROlMiAB4AuRAEZEAX3ZTsoSLASJ6GHPgLEyVGvQa0W7Dd179EDIQ0QBDIucuzshMEShZEAbVUBdMUOmIALzI6KxAA

Code 2
This also means that the program state can be contaminated (with bad practices?)

let i = 0;

function f() {
  console.log(i);
  return { 0: "a", 1: "b", 2: "c" } as { [key: number]: string };
}

const { [++i]: x } = f();

Expected behavior: 0

Actual behavior: 1

Playground Link:
https://www.typescriptlang.org/play/?target=1#code/DYUwLgBAlhC8EAYDcAoFAzArgOwMZigHtsJ0AKASggG8UBIXYgZ0NADphCBzMqC1CIIgAncJmElqiAFwQARAEM5AGggBGWXIBGKiACZNuORAC+EBUxoBtANYgAntOyYAtlpDCAutKZhhUbC4TVBM0RmxfGggrAGoYqG8IAA9TOFJKVHCWdk4eJIogA

Related Issues: #31469

Babel seems to compile it as f g as well: https://babeljs.io/repl#?babili=false&browsers=chrome%2068&build=&builtIns=usage&spec=false&loose=false&code_lz=GYVwdgxgLglg9mABMAFASkQbwFCL4iBAZzgBsBTAOlLgHMUAiYBtAbl3wCdyoROlMiAB4AuRAEZEAX3ZTsoSLASJ6GHPgLEyVGvQa0W7Dd179EDIQ1nZCYIlCyIA2qoC6YodMQBeZOlZAA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=false&presets=es2015%2Cflow&prettier=false&targets=&version=7.5.2&externalPlugins=

I don't understand what ECMAScript is saying about what it should be, but I believe this is relevant: https://tc39.es/ecma262/#sec-runtime-semantics-destructuringassignmentevaluation

In my opinion, TS's compilation makes the most sense. I don't know who is correct. Maybe TS is correct and everyone else is wrong. Again, I don't understand the ECMAScript document. But I can definitively say that TS differs from everyone else in this way.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScript

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions