Skip to content

Erroneous generated JS code when incrementing private (hashtag) fields with parenthesis #49935

@mfederczuk

Description

@mfederczuk

Bug Report

When incrementing a private class field (using the hashtag-syntax) and the field is put inside parenthesis while the increment operator is outside the parenthesis, invalid JavaScript code is generated.
e.g.: ++(this.#n)

🔎 Search Terms

private hashtag field increment parenthesis

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about private class fields and incrementing/decrementing

⏯ Playground Link

Playground link with relevant code

💻 Code

class Foo {
  #n: number = 0;

  inc() {
    ++(this.#n); // generated JS code here is erroneous
  }
}

const foo = new Foo();
foo.inc();

🙁 Actual behavior

The following code is generated:

++(__classPrivateFieldGet(this, _Foo_n, "f"))

which leads to the error: invalid increment/decrement operand when executing it, since the result of a function cannot be incremented/decremented.

The compiler seems to think that the variable-reference expression is read-only because of the parenthesis.

🙂 Expected behavior

The parenthesis should be ignored by the compiler and the correct code needs to be generated:

__classPrivateFieldSet(this, _Foo_n, (_a = __classPrivateFieldGet(this, _Foo_n, "f"), ++_a), "f")

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