Sub topic 9
strictPropertyInitialization in classes
This chapter covers the strictPropertyInitialization flag. It assumes you know class syntax, union types such as string | undefined, and that strictNullChecks is on. You should also know that "strict": true turns on a family of flags, which the earlier chapter on the strict umbrella covered.
What the flag checks
A class property declared with a type like string promises that reading it gives you a string. At runtime, a property that nothing assigns holds undefined. Without a check, the compiler lets you read it anyway.
strictPropertyInitialization closes that gap. It reports an error for every instance property that meets both conditions:
- Its type does not include
undefined. - It is not definitely assigned by the time the constructor finishes, either by an initializer or by an assignment in the constructor.
The error is TS2564: Property 'name' has no initializer and is not definitely assigned in the constructor.
The flag is part of strict. It only works when strictNullChecks is also on. If you enable it alone, tsc reports a configuration error instead of silently doing nothing.
{
"compilerOptions": {
"strictNullChecks": true,
"strictPropertyInitialization": true
}
}The basic rule
This class passes the check, because the constructor assigns the required property and the optional one needs no assignment:
class User {
name: string;
email?: string;
constructor(name: string) {
this.name = name;
}
}
const user = new User("Ada");
console.log(user.name, user.email);If you delete this.name = name;, the compiler reports TS2564 on name. The property email?: string has the type string | undefined, so it needs no assignment.
Four ways to satisfy the check
You have four fixes. Choose the one that matches what is actually true about the property.
Give it an initializer
If a sensible default exists, set it where you declare the property.
class Counter {
count = 0;
history: number[] = [];
}Assign it in the constructor
Use this when the value comes from the constructor arguments. A parameter property is shorthand that declares and assigns in one step, and the compiler counts it as initialized:
class Point {
constructor(
public x: number,
public y: number,
) {}
}Make absence part of the type
If the value really may be missing, say so. Either email?: string or email: string | undefined works. Callers must then check for undefined, which is the honest outcome.
Use a definite assignment assertion
Write ! after the property name to tell the compiler you will assign it before any read.
class Widget {
element!: HTMLElement;
mount(root: HTMLElement): void {
this.element = root;
}
}The compiler stops checking this property. If you were wrong, the failure appears at runtime as undefined.
How the compiler decides
The check follows control flow inside the constructor. It asks whether every path that reaches the end of the constructor has assigned the property.
flowchart TDThe diagram below shows the decision order.
Branches must all assign
An assignment inside only one branch is not enough:
class Session {
token: string; // error TS2564
constructor(isGuest: boolean) {
if (!isGuest) {
this.token = "user-token";
}
}
}Adding an else branch that assigns this.token, or assigning a default before the if, fixes it.
Helper methods are not followed
The analysis does not look inside methods that the constructor calls. This surprises many people:
class Settings {
values: Map<string, string>; // error TS2564
constructor() {
this.load();
}
private load(): void {
this.values = new Map();
}
}The compiler cannot prove load runs fully or only once, and a subclass could override it. You have two good choices. Return the value from the helper and assign it in the constructor, or initialize inline.
class SettingsFixed {
values: Map<string, string>;
constructor() {
this.values = SettingsFixed.load();
}
private static load(): Map<string, string> {
return new Map([["theme", "dark"]]);
}
}Using ! on values would also compile, but it gives up the check you just enabled.
What the flag does not check
The rule has limits worth knowing:
| Case | Checked? | Notes |
|---|---|---|
| Instance properties | Yes | The only target of this flag |
| `static` properties | No | Static fields are not covered by the constructor analysis |
| `abstract` properties | No | The subclass is responsible for providing them |
| `declare` fields | No | They emit no code, so no assignment is expected |
| Properties typed `any` or including `undefined` | No | They already accept `undefined` |
| Reads of `this.x` before assignment inside the constructor | Partly | Use before assignment is reported separately in some cases |
Because the constructor is the only place the compiler looks, the guarantee covers the end of construction. It does not cover code that runs earlier. For example, a base-class constructor can call an overridden method that reads a subclass property before that property is assigned. The compiler does not catch this.
Frameworks and the `!` escape hatch
Some libraries create objects without running your constructor assignments in the usual way. Dependency injection containers, ORMs, and UI frameworks often fill properties after construction. In those cases ! is a reasonable, documented choice:
class ProductRow {
id!: number;
title!: string;
}Keep these classes small and mark them clearly. Prefer a constructor or a factory function for classes that you construct yourself.
Interaction with class field semantics
With target set to ES2022 or later, useDefineForClassFields defaults to true. A field declaration such as name: string; then emits a real field initialized to undefined before the constructor body runs. That matches what the compiler assumes, since it treats the property as unassigned until your code sets it.
Be careful with subclasses that redeclare a base-class property. The redeclaration can reset the value to undefined under the new semantics. Use declare to describe a narrower type without emitting a field:
class Base {
value: string | number = 0;
}
class Derived extends Base {
declare value: number;
}Common mistakes
- Reaching for
!first. Try an initializer, a constructor assignment, or an optional type before you silence the check. - Marking a property optional only to quiet the error. This pushes
undefinedchecks onto every caller. - Assigning in a helper method and expecting the compiler to see it.
- Enabling the flag without
strictNullChecks, which produces a configuration error.
Exercise
A class has the property cache: Map<string, number>; and a constructor that calls this.init(), where init assigns this.cache = new Map(). The compiler reports TS2564. Give two fixes that keep the check meaningful, and say why init was not enough.
Show answer
The compiler does not analyze the bodies of methods called from the constructor, so it cannot prove the assignment happens. Fix 1: initialize inline with cache = new Map<string, number>();. Fix 2: have the helper return the map and assign it in the constructor, as in this.cache = this.createCache(); with createCache returning new Map(). Writing cache!: Map<string, number>; would compile but turns the check off for that property.
Exercise
Which of these properties produce TS2564 under strict? (a) a: string; with no constructor assignment, (b) b?: string;, (c) c: string | undefined;, (d) static d: string;
Show answer
Only (a). Properties (b) and (c) include undefined in their type, and static properties (d) are not checked by this flag.