Skip to content

Use 'static {}' for static fields when available and useDefineForClassFields is false #47707

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 4, 2022

Conversation

rbuckton
Copy link
Contributor

@rbuckton rbuckton commented Feb 2, 2022

This changes the emit for static field initializers to use static {} blocks when the target is ES2022+ and useDefineForClassFields is false. This allows us to preserve execution order for static fields, and keep static field assignments inside of the class body (granting them privileged access to private names).

This also correctly emits private static field initializers regardless of the useDefineForClassFields setting (since private fields use neither Set nor Define semantics).

For example:

// source
class C {
  static #x = 0;
  static y = this.#x;
  static [f()] = this.y;
}

// output
var _a;
class C {
  static { _a = f(); }
  static #x = 0;
  static { this.y = this.#x; }
  static { this[_a] = this.y; }
}

Fixes #45574

@typescript-bot typescript-bot assigned rbuckton and unassigned rbuckton Feb 2, 2022
@typescript-bot typescript-bot added Author: Team For Milestone Bug PRs that fix a bug with a specific milestone labels Feb 2, 2022
Copy link
Member

@sandersn sandersn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a weird combination of flags, but it's one I might use if I were writing a lot of classes. Not sure if that makes it more or less likely to be widely used.

@rbuckton rbuckton merged commit 3328feb into main Feb 4, 2022
@rbuckton rbuckton deleted the staticBlockExecutionOrder branch February 4, 2022 20:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Author: Team For Milestone Bug PRs that fix a bug with a specific milestone
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Execution order of static field initialization and static initialization blocks is not kept under target: esnext and useDefineForClassFields: false
3 participants