Course contentsShow
← TypeScript
Lesson 1059 of 1,79624. Classes in TypeScriptFree lesson

Static Blocks for Initialization

Use static initialization blocks to run complex setup logic when the class is first evaluated.

Static Blocks for Initialization

You'll learn: How to execute complex setup logic once when your class is first loaded, using static initialization blocks.

What Is a Static Block?

Sometimes static properties need more than just a simple assignment — they might require calculations, conditionals, or multi-step setup. A static initialization block is a special code block inside a class that runs exactly once when the class is first evaluated, before any instances are created.

Think of it like a "constructor for the class itself" rather than for instances. While constructors run every time you create an object with new, static blocks run exactly once when the JavaScript engine first encounters the class definition.

Basic Syntax

class Logger {
  static level: string;
  static startTime: number;

  static {
    // This code runs once when the class loads
    this.level = process.env.LOG_LEVEL || 'info';
    this.startTime = Date.now();
    console.log('Logger initialized');
  }
}

// The static block has already run by this point
console.log(Logger.level);    // 'info' (or env value)
console.log(Logger.startTime); // timestamp

When Static Blocks Shine

Use static blocks when you need to:

  • Compute initial values from multiple sources
  • Run conditional setup logic that doesn't fit in a simple assignment
  • Initialize multiple related static properties together
  • Handle errors during static initialization
class AppConfig {
  static version: string;
  static features: Set<string>;

  static {
    // Complex multi-step initialization
    const rawVersion = '1.2.3-beta';
    this.version = rawVersion.split('-')[0];

    this.features = new Set();
    if (this.version >= '1.0.0') {
      this.features.add('newUI');
      this.features.add('darkMode');
    }
  }
}

Multiple Static Blocks

You can have multiple static blocks in one class — they execute in order from top to bottom:

class Database {
  static connection: string;
  static poolSize: number;

  static {
    this.connection = 'localhost:5432';
  }

  static {
    // This runs after the first block
    this.poolSize = this.connection.includes('prod') ? 20 : 5;
  }
}

Key Takeaway: Static blocks let you run complex initialization logic exactly once when a class loads, giving you more power than simple property assignments while keeping setup code organized inside the class definition.