Course contentsShow
← TypeScript
Lesson 1199 of 1,79628. tsconfig in DepthFree lesson

strictPropertyInitialization: Required Class Properties

Forcing class properties to be initialized in the constructor or with definite assignment assertion.

strictPropertyInitialization: Required Class Properties

What you'll learn: How TypeScript ensures all class properties are initialized when strictPropertyInitialization is enabled.

What This Flag Does

When you enable strictPropertyInitialization in your tsconfig.json, TypeScript enforces that every class property must be definitely assigned a value either:

  1. At declaration (with an initializer)
  2. In the constructor
  3. With a definite assignment assertion (when you know better than TypeScript)

This prevents a common bug: accessing a property that was never initialized, resulting in undefined at runtime.

Why It Matters

Think of it like a safety checklist before takeoff. The compiler verifies that every property has been given a value before the class instance is used, preventing "forgot to initialize" bugs.

// With strictPropertyInitialization: true

class User {
  name: string;  // ❌ Error: Property 'name' has no initializer
  age: number;   // ❌ Error: Property 'age' has no initializer
}

How to Satisfy the Requirement

Option 1: Initialize at declaration

class User {
  name: string = "";
  age: number = 0;
}

Option 2: Initialize in constructor

class User {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

Option 3: Definite assignment assertion (when you initialize elsewhere)

class Component {
  element!: HTMLElement;  // The ! tells TypeScript "trust me"

  init() {
    this.element = document.getElementById('root') as HTMLElement;
  }
}

The Trade-off

The definite assignment assertion (!) is an escape hatch—use it when you genuinely initialize the property through a method called immediately after construction, but be careful: you're telling TypeScript to skip the safety check.

Key Takeaway: strictPropertyInitialization prevents uninitialized property bugs by requiring proof that every class property gets a value before use—either through initializers, constructor assignment, or explicit assertion.