Skip to content

Class static block does not allow forward reference to static method #45932

Closed
@fwienber

Description

@fwienber

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

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