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

Property Initialization Requirements

Understand strictPropertyInitialization and when properties must be initialized in the constructor.

Property Initialization Requirements

What you'll learn: How TypeScript's strictPropertyInitialization flag ensures class properties are properly initialized, preventing undefined access bugs.

The Core Idea

In JavaScript, class properties can exist in a weird "undefined but declared" state if you forget to initialize them. TypeScript's strictPropertyInitialization compiler option (enabled by strict) catches this at compile-time by requiring that every property either:

  1. Has an explicit initializer
  2. Is initialized in the constructor
  3. Is marked as optional with ?
  4. Uses the definite assignment assertion !

Think of it like a safety inspector checking that every room in a building has working lights before issuing an occupancy permit—you can't just declare there's a light, you must prove it exists.

When Properties Must Be Initialized

With strictPropertyInitialization enabled, TypeScript enforces that non-optional properties have values:

class User {
  name: string;      // ❌ Error: Property 'name' has no initializer
  age: number;       // ❌ Error: Property 'age' has no initializer
  email?: string;    // ✅ OK: Optional properties can be undefined
  role: string = 'user';  // ✅ OK: Has initializer
}

You must initialize in the constructor:

class User {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;  // ✅ Initialized here
    this.age = age;    // ✅ Initialized here
  }
}

Why This Matters

Without this check, you'd create instances with undefined properties that your type system claims are strings or numbers, leading to runtime errors TypeScript should prevent.

Key Takeaway: With strictPropertyInitialization, TypeScript requires all class properties to be initialized at declaration, in the constructor, or explicitly marked optional—preventing undefined property access bugs before runtime.