Skip to content

Generated code is incorrect for function with destructuring and default parameterΒ #47079

@evanw

Description

@evanw

Bug Report

πŸ”Ž Search Terms

default destructuring scope parameter argument ReferenceError

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

function foo({a, ...x}, b = a) {
  return b
}
console.log(foo({a: 1}))

πŸ™ Actual behavior

If you run TypeScript's output, you get ReferenceError: a is not defined. This is the problematic output:

"use strict";
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
function foo(_a, b = a) {
    var { a } = _a, x = __rest(_a, ["a"]);
    return b;
}
console.log(foo({ a: 1 }));

Notice how b = a is evaluated before { a } = _a.

πŸ™‚ Expected behavior

If you run the JavaScript directly you should get 1, so TypeScript's output should do that too.

Additional context is here: evanw/esbuild#1826. I got a report about this bug in esbuild and it turns out TypeScript has the same bug, so I'm filing it here too. My apologies if this is a duplicate (I couldn't find one that had already been filed).

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions