Sub topic 5
Strict Property Initialization and Definite Assignment
This chapter assumes you can write basic TypeScript types, declare a class with fields and a constructor, and read strict compiler options. It covers the check that stops a class field from being undefined when its type says it can't be. It also covers the ways to satisfy that check and the cases where you have to tell the compiler to trust you.
The problem the check solves
In JavaScript, a declared field that nobody assigns holds undefined. If TypeScript allowed a field typed string to stay unassigned, user.name.toUpperCase() would compile and then crash at runtime.
Strict property initialization closes that gap. For every instance field whose type does not include undefined, the compiler must be able to prove that the field is assigned by the end of the constructor, or that it has an initializer.
The check is on when both strict and strictNullChecks are on. It is controlled by its own flag, strictPropertyInitialization, which strict turns on. It requires strictNullChecks, and enabling it without that option produces a configuration error.
{
"compilerOptions": {
"strict": true
}
}What the compiler reports
class User {
name: string;
age: number;
constructor(name: string) {
this.name = name;
// age is never assigned
}
}The compiler reports Property 'age' has no initializer and is not definitely assigned in the constructor. (error 2564). It points at the field declaration, not at the constructor.
Four ways to satisfy the check
1. Assign an initializer
class Session {
token: string = "";
retries = 0;
startedAt = new Date();
}An initializer runs before the constructor body. TypeScript also infers the field type from it, so retries is a number.
2. Assign in the constructor
class Config {
host: string;
port: number;
constructor(host: string, port = 8080) {
this.host = host;
this.port = port;
}
}The compiler uses control flow analysis. A field must be assigned on every path that reaches the end of the constructor.
class Connection {
url: string; // Error 2564
constructor(secure: boolean) {
if (secure) {
this.url = "https://example.com";
}
// the else path leaves url unassigned
}
}Adding an else branch, or a default assignment before the if, fixes this.
3. Include `undefined` in the type
class Cache {
value: string | undefined;
lastError?: Error;
}If undefined is a legitimate state, say so in the type. Callers must then handle it before using the value. This is usually the most honest option when a value really does arrive later.
4. Use the definite assignment assertion
class Widget {
element!: HTMLElement;
init(): void {
this.element = document.createElement("div");
}
}The ! after the field name tells the compiler that the field will be assigned before it is read, even though it cannot prove this. The compiler stops checking that field, so you are responsible for the guarantee.
Where the compiler cannot see the assignment
The check only looks at the constructor body. Assignments made in a method that the constructor calls are invisible to it.
class Store {
items: string[]; // Error 2564
constructor() {
this.reset();
}
reset(): void {
this.items = [];
}
}The code is correct at runtime, but the compiler does not follow calls. You have three options. You can assign directly in the constructor and let reset assign again. You can add an initializer such as items: string[] = []. You can also add ! to the field.
Common situations where ! is a reasonable choice:
- A framework injects the value after construction (dependency injection containers, ORMs, UI frameworks).
- The value is set in a lifecycle method such as
init()orngOnInit(). - A test class sets fields in a
beforeEachhook.
In each case, the risk is that someone reads the field too early and gets undefined with no compiler warning.
Definite assignment for local variables
The same ! syntax exists on local variables, where it solves a related problem. The compiler reports use-before-assign errors for variables declared without a value.
let total: number;
function compute(): void {
total = 42;
}
compute();
console.log(total); // Error: Variable 'total' is used before being assigned.let total!: number;
function compute(): void {
total = 42;
}
compute();
console.log(total); // 42Prefer restructuring the code so the variable gets a value at declaration. Use ! only when that is not practical.
Interaction with other features
Parameter properties
A parameter property (constructor(public name: string)) assigns the field automatically, so it always satisfies the check. This is one reason parameter properties are a common way to avoid the error.
Inheritance
Each class is checked for its own fields. A subclass that redeclares a base class field is checked again.
class Base {
id: string = "base";
}
class Derived extends Base {
declare id: string; // type-only redeclaration, no emit, no check
}The declare modifier on a field states that the type is refined without creating a new field at runtime. It matters when useDefineForClassFields is on, which is the default when the target is ES2022 or later. In that mode, a plain redeclaration such as id: string; in the subclass emits a field definition that sets id to undefined after the base constructor runs, which overwrites the value the base class set.
Abstract and static fields
Abstract properties have no implementation, so they are not checked. Static properties are not covered by strict property initialization. A static field typed string that is never assigned does not produce error 2564.
Choosing an approach
| Situation | Best option | Column |
|---|---|---|
| Value known when the object is created | Constructor assignment or initializer | |
| A sensible default exists | Initializer | |
| The value may truly be absent | `T \ | undefined` or `?` |
| Set later by a framework or lifecycle hook | `!` with a comment explaining why | |
| Set by a helper method called from the constructor | Inline the assignment, or use `!` |
Common mistakes
- Turning off
strictPropertyInitializationfor the whole project to silence a few errors. This removes the check from every class. - Using
!on fields that the constructor could simply assign. - Assuming
!produces a runtime check. It is erased during compilation and has no effect on the emitted JavaScript. - Expecting the compiler to follow assignments made in helper methods or callbacks.
Exercise
A class has the field connection: Database; and a constructor that calls this.connect(). The connect() method assigns this.connection. The compiler reports error 2564 on the field. Give two ways to fix it, and say which you prefer and why.
Show answer
One fix is to assign the field directly in the constructor, for example this.connection = createConnection();, because the compiler only follows assignments in the constructor body. Another is to add !, as in connection!: Database;, which tells the compiler the field will be assigned. The direct assignment is better because it keeps the compiler's check active and removes the risk of a read-before-assign bug. Use ! only if the assignment cannot move into the constructor.
Exercise
Why does a static field typed string with no initializer not trigger error 2564, and what does that suggest about how you should treat such fields?
Show answer
Strict property initialization only checks instance fields that must be assigned by the end of a constructor. Static fields are not covered, so the compiler gives no warning. You should give static fields an initializer or include undefined in their type so they cannot be read as undefined by accident.