DEV Community 👩‍💻👨‍💻

Cover image for Typescript Static Class Blocks
Lioness100
Lioness100

Posted on

Typescript Static Class Blocks

Class static blocks came to Typescript in v4.4, and is on the roadmap for becoming an official ECMAScript feature as well! It's used to contain any initialization for the class. The reason this feature is so helpful is because it can access all private internals of the class it's in, as well!

class Unicorn {
  static #isShiny = false;
  static #shinyLevel = 0;

  static {
    const { hasRainbowHorn, hasRainbowTail } = getData(Unicorn);
    if (hasRainbowHorn || hasRainbowTail) {
      // access and modify internals!
      this.#isShiny = true;
      this.#shinyLevel = Math.random();
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

You can create multiple static blocks in a class, which will be executed in sequential order.

This feature is definitely small - but I thought it was cool and wanted to share it with you all. However, since this post would be so short, I though I should add a...

Half Related Tip ✨

While we're talking about static classes: do you know the best way to make a class unconstructable? This might come in handy for a utility class with only static methods. The most popular method is:

class Util {
  public constructor() {
    throw new Error('Do not initialize this class!');
  }
}
Enter fullscreen mode Exit fullscreen mode

However, you can shorten it by just extending null:

class Util extends null {}

new Util(); // TypeError!
Enter fullscreen mode Exit fullscreen mode

💖

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.