MediumClasses & OOP📖 Theory Question

What are static members and class fields in TypeScript?

💡

Hint

static members belong to the class itself, not instances; class fields vs constructor assignments have subtle initialization order differences

Full Answer

Static members belong to the class itself, not to any instance. Accessed via the class name.

class Counter {
  static count = 0;  // shared across all instances
  id: number;

  constructor() {
    Counter.count++; // increment class-level counter
    this.id = Counter.count;
  }

  static reset() {
    Counter.count = 0;
  }

  static getInstance() {
    return new Counter();
  }
}

const a = new Counter(); // Counter.count = 1
const b = new Counter(); // Counter.count = 2
console.log(Counter.count); // 2

Counter.reset();
console.log(Counter.count); // 0

Class fields vs constructor assignment:

class Example {
  // Class field — initialized BEFORE constructor body
  x = 10;
  y = this.x * 2; // ✅ x is already 10

  // Method defined as field — each instance gets its own copy
  handleClick = () => {
    console.log(this.x); // 'this' is always correct — no binding needed
  };

  constructor() {
    // Class fields are set BEFORE this runs
    console.log(this.x); // 10
  }
}

// vs prototype method — shared across all instances
class ExampleProto {
  handleClick() {
    // 'this' depends on how it's called — may need .bind()
    console.log(this);
  }
}
💡 Arrow function class fields (like handleClick = () => {}) solve the React event handler binding issue — no need for .bind(this) in the constructor. The trade-off is each instance gets its own function copy rather than sharing a prototype method.

More Classes & OOP Questions

EasyWhat are access modifiers in TypeScript — public, private, protected, readonly?→EasyWhat are abstract classes in TypeScript and when should you use them?→EasyWhat is the difference between implements and extends in TypeScript?→EasyHow do decorators work in TypeScript, and what are they used for?→

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint