Description
Bug Report
🔎 Search Terms
class static blocks, forward reference, incorrect compiler error
🕗 Version & Regression Information
4.4.2 + nightly (4.5.0-dev20210910)
- I was unable to test this on prior versions because the feature is new in 4.4
⏯ Playground Link
Playground link with relevant code
💻 Code
class A {
static {
A.doSomething();
}
static doSomething() {
console.log("gotcha!");
}
}
🙁 Actual behavior
Compiler error in line 3: "Property 'doSomething' is used before its initialization.(2729)"
The code works as-is in native JavaScript, tested in Firefox Developer Edition.
The rewrites for class static blocks in Babel as well as in TypeScript itself also work. Both execute the static block's code at a time where static methods of the class are already available.
🙂 Expected behavior
No compiler error, because everything's fine.
A forward reference to a static field, however, should be an error (I guess).
Workaround
Fall back to the way class static blocks could be emulated before they were supported:
Define an unused #-private static constant whose initializer is an immediate-evaluating function.
class A {
static #_ = (() => {
A.doSomething();
})();
static doSomething() {
console.log("gotcha!");
}
}
Playground link for workaround
Looks ugly, but works in the desired execution order and produces no compiler error.
Possibly related issues
- Execution order of static field initialization and static initialization blocks is not kept under target: esnext and useDefineForClassFields: false Execution order of static field initialization and static initialization blocks is not kept under target: esnext and useDefineForClassFields: false #45574
- Statements in class static blocks do not narrow types Statements in class static blocks do not narrow types #44949