Skip to content

Statements in class static blocks do not narrow types #44949

Closed

Description

@AumyF

Bug Report

🔎 Search Terms

control flow analysis, class static blocks

🕗 Version & Regression Information

  • v4.4.0-beta
  • v4.4.0-dev.20210708
  • This is the behavior in every version I tried, and I reviewed the proposal
  • I was unable to test this on prior versions because class static blocks were added in 4.4.0

⏯ Playground Link

Playground link with relevant code

💻 Code

let foo: number;

class C {
  static {
    foo = 3;
  }
}

console.log(foo);

🙁 Actual behavior

An error Variable 'foo' is used before being assigned.(2454) occurs at line 10, console.log(foo).

🙂 Expected behavior

Code compiles without errors.

Activity

  1. tchetwin commented on Jul 14, 2021

    @tchetwin

    I accidentally duplicated this in #45023. Carrying over a point from there:

    "Side effects" in initialization of static fields already behaved similarly (since ~forever):

    let c: number;
    class C {
      static f = (c = 10);
    }
    c; // Variable 'c' is used before being assigned.(2454)
  2. fwienber commented on Sep 13, 2021

    @fwienber

    What about this even simpler case:

    class Foo {
        static {
            Foo.doSomething(); // Error: "Property 'doSomething' is used before its initialization.(2729)"
        }
    
        // this is how Babel rewrites the above:
        static #_ = (() => {
            Foo.doSomething(); // Now, the forward reference is allowed!
        })();
    
        static doSomething(): void {
           console.log("gotcha!");
        }
    }
    

    This code on TypeScript Playground
    Are class static blocks supposed to be more strict in this regard?
    The Babel rewrite for class static blocks is to define an unused, #private static variable whose initializer is a self-evaluating arrow function. Using the rewrite, TypeScript does not complain about the forward reference.
    At runtime, both variants work.
    It seems to me that the TypeScript error should not be raised in this case.
    Is this the same problem as above or should I create a separate issue?

  3. Zzzen commented on Sep 14, 2021

    @Zzzen
    Contributor

    I believe that's a separate issue.

  4. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptFix AvailableA PR has been opened for this issueHelp WantedYou can do thisRescheduledThis issue was previously scheduled to an earlier milestone

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions