strictPropertyInitialization in TypeScript
What you'll learn: How to enable compiler checks that require all class properties to be initialized either in the constructor or with a definite assignment assertion.
What Is strictPropertyInitialization?
The strictPropertyInitialization flag ensures that every class property without an explicit undefined type is given a value before the constructor finishes. This catches a common bug: declaring a property but forgetting to initialize it, leading to unexpected undefined values at runtime.
When this flag is enabled (it's included in strict), TypeScript acts like a helpful assistant checking: "You said this property would always have a value, but I don't see where you set it. Are you sure?"
How It Works
Without this flag, you can declare properties and "promise" they have a type, but never actually initialize them:
class User {
name: string; // Says it's a string, but never assigned!
constructor() {
// Oops, forgot to set name
}
}
const user = new User();
console.log(user.name.toUpperCase()); // Runtime error: undefined!
With strictPropertyInitialization, TypeScript catches this at compile time. You must either:
- Initialize in the constructor:
class User {
name: string;
constructor(name: string) {
this.name = name; // ✓ Initialized
}
}
- Initialize at declaration:
class User {
name: string = "Unknown";
}
- Use definite assignment assertion (!):
class User {
name!: string; // "I promise this gets set elsewhere"
constructor() {
this.initializeName();
}
private initializeName() {
this.name = "Default";
}
}
The Safety Net
Think of this flag like a seatbelt warning in your car. It reminds you to fasten the belt (initialize properties) before you start driving (use the class). The definite assignment assertion (!) is like clicking the seatbelt buckle without actually fastening it—you're telling the compiler "trust me," so use it carefully.
Key Takeaway: strictPropertyInitialization prevents a major source of undefined bugs by requiring explicit initialization of class properties, ensuring your objects always have the values their types promise.