Sub topic 10
Class properties and definite assignment
This chapter assumes you know basic TypeScript classes, type annotations, constructors, and union types. It also assumes that strictNullChecks is enabled. The examples focus on the related option strictPropertyInitialization, which checks that class properties receive values before an object can use them.
Why class properties need special checking
Consider this class:
class User {
name: string;
constructor() {
// No assignment to name
}
}
const user = new User();
console.log(user.name.toUpperCase());The type says name is always a string, but the constructor leaves it undefined at runtime. With strict settings, TypeScript reports an error:
Property 'name' has no initializer and is not definitely assigned in the constructor.The compiler cannot allow a property to promise string while the object may contain no value. This check is controlled by strictPropertyInitialization. The strict option enables it when strictNullChecks is also enabled.
{
"compilerOptions": {
"strict": true
}
}Assign every required property
The usual solution is to assign the property in every constructor path.
class Label {
text: string;
constructor(text?: string) {
this.text = text ?? "none";
}
}
const first = new Label("Important");
const second = new Label();
console.log(first.text); // Important
console.log(second.text); // noneThe ?? operator uses "none" only when text is null or undefined. The property is therefore always a string after construction.
A parameter property combines a property declaration with a constructor parameter:
class Account {
constructor(public readonly id: string) {}
}
const account = new Account("acct-42");
console.log(account.id);Here, TypeScript creates the id property and assigns the constructor argument to it. readonly prevents later assignment through the property.
Optional properties are a different promise
Use ? when a property is allowed to be absent:
interface Settings {
theme?: string;
}
class Panel {
settings?: Settings;
constructor(settings?: Settings) {
this.settings = settings;
}
themeName(): string {
return this.settings?.theme ?? "default";
}
}settings has the type Settings | undefined. Code must check it, use optional chaining, or provide a fallback before treating it as present.
Do not add ? merely to silence an initialization error. An optional property communicates a real runtime possibility. If every Panel should have settings, initialize it instead.
Definite assignment assertions
Sometimes a class receives its property value through a method or framework lifecycle that TypeScript cannot see:
class Controller {
private service!: Service;
connect(service: Service): void {
this.service = service;
}
run(): void {
this.service.start();
}
}
class Service {
start(): void {
console.log("started");
}
}The ! after service is a definite assignment assertion. It tells the compiler, “Trust me; this property will be assigned before it is read.”
It does not assign anything at runtime. Calling run() before connect() still causes an error because this.service is actually undefined.
Prefer a constructor when possible:
class SafeController {
constructor(private readonly service: Service) {}
run(): void {
this.service.start();
}
}Use ! only when an external lifecycle guarantees initialization and that guarantee is difficult to express in the class design. Otherwise, make the state explicit with Service | undefined and check it, or require the dependency in the constructor.
How the checks fit together
Exercise
Exercise
In the following class, should you use !, ?, or a constructor assignment? Explain and rewrite it safely: class Report { data: string; load(): void { this.data = "ready"; } }
Show answer
Use a constructor assignment if a report must always be ready, such as constructor(public readonly data: string) {}. If loading is genuinely delayed, use data?: string or data: string | undefined and check it before reading. Do not use ! unless another system guarantees that load() always runs first.