Sub topic 5
Strict Property Initialization and Definite Assignment
This chapter assumes basic TypeScript types, JavaScript classes, constructors, and the this keyword. It also assumes you can run TypeScript with strict checking enabled.
Why initialization matters
A class field should contain a valid value before another method uses it. With strictPropertyInitialization, TypeScript checks that each non-optional field is initialized when an instance is created.
This option is enabled by the broader strict option:
{
"compilerOptions": {
"strict": true
}
}Consider this class:
class User {
name: string;
constructor() {
// Error: Property 'name' has no initializer and is not definitely assigned in the constructor.
}
}The field is declared as a string, so it cannot start as undefined. TypeScript therefore requires an initializer or a constructor assignment.
You can initialize the field where you declare it:
class User {
name = "Unknown";
}Or assign it in every possible constructor path:
class User {
name: string;
constructor(name?: string) {
if (name) {
this.name = name;
} else {
this.name = "Unknown";
}
}
}The important rule is that TypeScript must be able to prove that the field receives a value before the constructor finishes.
flowchart TD
A[Declare a required field] --> B{Is it initialized?}
B -->|At declaration| C[Safe]
B -->|In every constructor path| C
B -->|No| D[Compile-time error]
B -->|Use ! assertion| E[Developer promises initialization]Optional fields and `undefined`
If a field may not have a value, express that in its type:
class Profile {
displayName?: string;
bio: string | undefined;
constructor() {
this.bio = undefined;
}
}The ? marks displayName as optional. Its value can be missing or undefined. The union type on bio says that the field exists but may contain undefined.
Do not silence an initialization error by adding | undefined unless an uninitialized value is part of the design. That changes the API and forces callers to handle the missing value.
Definite assignment assertions
A definite assignment assertion is an exclamation mark after a field name:
class Service {
private client!: { request(): string };
start(): void {
this.client = {
request: () => "done"
};
}
run(): string {
return this.client.request();
}
}
const service = new Service();
service.start();
console.log(service.run()); // doneThe ! tells the compiler, “Initialization happens elsewhere.” TypeScript stops checking that field, but JavaScript does not add any runtime protection. Calling run() before start() would fail.
Use this assertion only when a framework, lifecycle method, or constructor helper guarantees initialization. Prefer a constructor assignment or an explicit optional type when possible.
Exercise
Why does name!: string compile without a constructor assignment, and what risk does it introduce?
Show answer
The ! asserts that the developer will initialize name before use. If that promise is false, the field can still be undefined at runtime.