Sub topic 10
Class properties and definite assignment
This chapter assumes you know class syntax in TypeScript, union types such as string | undefined, and how to turn on strictNullChecks in tsconfig.json. You should also know that a property you never assign reads as undefined at runtime.
The problem: fields that start out empty
In JavaScript, a class field that nobody assigns holds undefined. TypeScript without strictNullChecks lets you declare that field as string anyway, and the lie only shows up when some code calls a method on undefined.
With strictNullChecks on, TypeScript closes this gap using a second option, strictPropertyInitialization. It checks that every property whose type does not include undefined is assigned before the constructor finishes. The strict flag turns on both options.
{
"compilerOptions": {
"strict": true
}
}If you enable the options one at a time, note that strictPropertyInitialization has no effect unless strictNullChecks is also on. The compiler reports an error if you set the first without the second.
What the compiler checks
Here is the smallest failing case.
class Counter {
count: number;
// Error TS2564: Property 'count' has no initializer
// and is not definitely assigned in the constructor.
}The compiler accepts the property if one of these is true:
- The declaration has an initializer.
- The constructor assigns it on every code path.
- Its type includes
undefined. - You tell the compiler to trust you with
!, covered below.
The next example shows the first three.
class Counter {
count = 0; // initializer
label: string; // assigned in the constructor
lastError: string | undefined; // type admits undefined
constructor(label: string) {
this.label = label;
}
}
const c = new Counter("clicks");
console.log(c.count, c.label, c.lastError); // 0 clicks undefinedNote that a property of type string | undefined does not need an initializer. Every read of lastError must handle undefined, which is the cost of choosing this option.
You can also use parameter properties, which declare and assign a field in one step. The compiler counts them as assigned.
class Point {
constructor(
public readonly x: number,
public readonly y: number,
) {}
}Every path must assign
The compiler uses control flow analysis in the constructor. If any branch can leave the property unassigned, you get the same TS2564 error.
class Connection {
host: string; // Error TS2564
constructor(host?: string) {
if (host !== undefined) {
this.host = host;
}
}
}The fix is to cover the other branch, usually with ?? or an else.
class Connection {
host: string;
constructor(host?: string) {
this.host = host ?? "localhost";
}
}Loops and try blocks work the same way. The compiler cannot assume a loop body runs, so an assignment inside a for loop does not count.
Assignment through a method does not count
The check is local to the constructor body. If the constructor calls a method that sets the property, the compiler does not follow the call.
class Session {
token: string; // Error TS2564
constructor() {
this.init();
}
private init(): void {
this.token = "abc";
}
}The compiler cannot know that init is called before any other code reads token. A subclass could override init, or someone could call it later. The restriction exists because it is safer. You can resolve it in three ways:
- Assign inline in the constructor.
- Have the helper return the value and assign it in the constructor:
this.token = this.createToken();. - Use a definite assignment assertion, if you are certain.
class Session {
token: string;
constructor() {
this.token = Session.createToken();
}
private static createToken(): string {
return "abc";
}
}A static helper has the added benefit that it cannot touch this, so it cannot read half-built state.
The definite assignment assertion
Some designs assign fields after construction. A dependency injection container might set them, a UI framework might call a lifecycle hook, or a test might fill them in a setup function. For these cases, put ! after the property name.
class Widget {
element!: HTMLElement;
mount(root: HTMLElement): void {
this.element = root;
}
show(): void {
this.element.hidden = false;
}
}The ! here is a definite assignment assertion. It sits in the declaration (element!: HTMLElement), not on a use of the value. It tells the compiler "this will be assigned before it is read" and removes the TS2564 error. It does not add any runtime check.
If you call show() before mount(), the program throws TypeError: Cannot read properties of undefined. The type system will not warn you. You have moved the responsibility from the compiler to yourself.
This is different from the non-null assertion on an expression (widget.element!.hidden), which the previous chapter covered. Both use !, and both silence the compiler without checking anything. They apply in different places.
Choosing between the options
Before reaching for !, ask whether the design can make the invalid state impossible. The table compares the usual choices.
| Approach | Safety | Cost |
|---|---|---|
| Initializer or constructor assignment | The compiler proves it | Needs the value at construction time |
| Type includes `undefined` | Every read must be checked | Narrowing code at each use |
| Definite assignment assertion `!` | None; you promise | Possible runtime `TypeError` |
| Factory function with private constructor | The compiler proves it | A different way to create objects |
The flowchart below turns the table into a decision procedure.
The factory option deserves an example, because it is often the best fix for asynchronous setup. The constructor receives finished values, so the object can never exist in a half-built state.
class Config {
private constructor(readonly values: Map<string, string>) {}
static async load(): Promise<Config> {
// Stand-in for reading a file or calling an API.
const values = new Map<string, string>([["mode", "dev"]]);
return new Config(values);
}
get(key: string): string | undefined {
return this.values.get(key);
}
}
async function main(): Promise<void> {
const config = await Config.load();
console.log(config.get("mode") ?? "unset"); // dev
}
main();Code outside the class cannot call new Config(...) because the constructor is private. Anything that holds a Config has a fully loaded one.
Local variables have a similar rule
The same idea applies to local variables. If a variable's type does not include undefined, you cannot read it before the compiler can prove it was assigned.
let total: number;
console.log(total); // Error TS2454: Variable 'total' is used before being assigned.This check works even without strictNullChecks for some cases, but the rules for what counts as assigned are the same control flow rules you saw for constructors. Assigning in an if without an else leaves the variable possibly unassigned after the if.
function pick(flag: boolean): number {
let result: number;
if (flag) {
result = 1;
} else {
result = 2;
}
return result; // fine: both branches assign
}A local variable can also take the ! assertion, written let x!: number;. The compiler then stops tracking it. You rarely need this. A closure that assigns the variable is the usual cause, and restructuring the code is generally better.
let value!: number;
function setValue(): void {
value = 42;
}
setValue();
console.log(value + 1); // 43Without the !, the compiler would report TS2454 on the console.log line, because it does not follow the call to setValue.
Gotcha: class fields and emit
Newer compiler targets (ES2022 and later, or any setting where useDefineForClassFields is true) emit a real field definition for every declared property. This affects ! fields in subclasses.
class Base {
constructor() {
this.init();
}
init(): void {}
}
class Child extends Base {
name!: string;
init(): void {
this.name = "set by base constructor";
}
}
console.log(new Child().name);With field definitions emitted, name!: string becomes a field initialized to undefined after the Base constructor runs. That overwrites the value init just set, so the program prints undefined. The type says string. If you need a field typed in a subclass but assigned by a base class, use declare name: string;. A declare field produces no emitted code, so it cannot reset the value.
Common errors
- Enabling
strictPropertyInitializationalone. It requiresstrictNullChecks, and the compiler reports a configuration error otherwise. - Expecting a helper method to count as assignment. Only code in the constructor body counts.
- Adding
!to silence the error, then reading the field in the constructor before a hook runs. The read compiles and returnsundefined. - Typing a field as
string | undefinedand then putting!on every use. This combines the costs of both approaches. Narrow the value once, or redesign. - Forgetting that arrow-function properties and property initializers run in order. An initializer can read a field declared above it, but not one declared below it.
Summary of the rules
strictPropertyInitializationneedsstrictNullChecksand is part ofstrict.- A property is fine if it has an initializer, is assigned on every path of the constructor, or has
undefinedin its type. - The compiler does not follow method calls from the constructor.
name!: Typeis an unchecked promise. Use it for framework-managed fields, and prefer a static factory when you control construction.- In subclasses with emitted field definitions, a
!field can be reset toundefined. Usedeclarethere.
Exercise
This class fails to compile under strict. Name the error code, explain why the compiler rejects it, and give two different fixes, one that proves safety to the compiler and one that does not.
class Cache {
entries: Map<string, number>;
constructor() {
this.reset();
}
reset(): void {
this.entries = new Map();
}
}
Show answer
The compiler reports TS2564: Property 'entries' has no initializer and is not definitely assigned in the constructor. It only analyzes assignments in the constructor body, so the assignment inside reset does not count, even though the constructor calls reset. A fix the compiler can prove is to initialize the field directly: entries = new Map<string, number>();, or to assign this.entries = new Map(); in the constructor and have reset reassign it later. A fix that relies on trust is entries!: Map<string, number>;, which removes the error but leaves you responsible for making sure nothing reads entries before reset runs.
Exercise
A class loads its data from a network call. Describe how a private constructor and a static async method remove the need for ! or | undefined on the data field.
Show answer
The constructor takes the loaded data as a parameter and assigns it, so the field is always initialized and has a plain non-undefined type. The static async method performs the network call, waits for the result, and then calls new with it. Because the constructor is private, no other code can create an instance without going through the static method, so no instance can exist before its data has loaded.