TypeScript: Class marked as unused when used in a static block

πŸ”Ž Search Terms

class unused static field block

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.5.0-dev.20240303#code/DYUwLgBAQsCu4AsD2SwBEQDcCWBjEA+rgE4gCGYIA3ALABQuwZAzs9HIiulniBAN70IEAMTYAJgEIAXBGZhi2AHYBzWnSFywFPKLLBgSAO4BhJEvnFYuSAF4IAM33Nq9TQAdFmCn1znL1mBIxAAUAJQCmsLYDhAhkjDwYMioGDj4AHQi+oam-gqBEYJ0wqUQycTGEEogRhAAosSVoQBEAJpIsBC4ZEpKqBDK8r1g2D7lCNhsjCxs4tikNsAAni1h6mUAvprbGiVaOriR+8KJnKk8+ESk4-YhErKWyioRtgB8x2WnHMlcabxZHLGMwWAo2CD2AquE6lPygiDiS58ew1OpnX4XdIgcIbL7olLcLGAgzA-JWcH2JzAFy4sqIolicQQwbiWmlUhgWDEJQIpFsza43aaFTgFnhT7s8BcnnJKZZCSC+hCuigSBkZkAJnU9HxfyR13IlBCLTIZDW2roIAAHu5gpB+JsgA

πŸ’» Code

let BluethootDevice_create;
class BluethootDevice {
  #id!: string;

  static #allowConstruct = false;

  private constructor() {
    if (!BluethootDevice.#allowConstruct) {
      throw new Error("You cannot instantiate this class directly");
    }
  }

  static {
    BluethootDevice_create = (id: string) => {
      BluethootDevice.#allowConstruct = true;
      const device = new BluethootDevice();
      BluethootDevice.#allowConstruct = false;
      device.#id = id;
      return device;
    };
  }

  get id() {
    return this.#id;
  }
}

let a = 2;

BluethootDevice_create("aa");

export {}

πŸ™ Actual behavior

The class BluethootDevice is marked as unused, but it’s used by the BluethootDevice_create function

πŸ™‚ Expected behavior

BluethootDevice should not be marked as unused

Additional information about the issue

No response

About this issue

  • Original URL
  • State: open
  • Created 4 months ago
  • Comments: 15 (5 by maintainers)

Most upvoted comments

β€œstatic block is IIFE” feels like the right view of this, since it runs on block evaluation rather than on first constructor call.