Strict Property Initialization in TypeScript
TypeScript 2.7 introduced a new compiler option for strict property initialization checks in classes. If the --strictPropertyInitialization
flag is enabled, the type checker verifies that each instance property declared in a class either
- has a type that includes
undefined
, - has an explicit initializer, or
- is definitely assigned to in the constructor.
The --strictPropertyInitialization
option is part of the family of compiler options that is enabled automatically when the --strict
flag is set. As with all the other strict compiler options, you can set --strict
to true
and selectively opt out of strict property initialization checks by setting --strictPropertyInitialization
to false
.
Note that the --strictNullChecks
flag must be set (either directly or indirectly via --strict
) in order for --strictPropertyInitialization
to have any effect.
Alright, let's see strict property initialization checks in action. Without the --strictPropertyInitialization
flag enabled, the following code type-checks just fine, but produces a TypeError
at runtime:
class User {
username: string;
}
const user = new User();
// TypeError: Cannot read property 'toLowerCase' of undefined
const username = user.username.toLowerCase();
The reason for the runtime error is that the username
property holds the value undefined
because there's no assignment to that property. Therefore, the call to the toLowerCase()
method fails.
If we enable --strictPropertyInitialization
, the type checker raises an error:
class User {
// Type error: Property 'username' has no initializer
// and is not definitely assigned in the constructor
username: string;
}
Let's look at four different ways we can properly type our User
class to make the type error go away.
#Solution #1: Allowing undefined
One way to make the type error go away is to give the username
property a type that includes undefined
:
class User {
username: string | undefined;
}
const user = new User();
Now, it's perfectly valid for the username
property to hold the value undefined
. Whenever we want to use the username
property as a string, though, we first have to make sure that it actually holds a string and not the value undefined
, e.g. using typeof
:
// OK
const username =
typeof user.username === "string" ? user.username.toLowerCase() : "n/a";
Alternatively, we can use optional chaining (the ?.
operator) to only call the toLowerCase()
method if the username
property holds a non-nullish value. We can combine that with nullish coalescing (the ??
operator) to provide the fallback value:
// OK
const username = user.username?.toLowerCase() ?? "n/a";
#Solution #2: Explicit Property Initializer
Another way to make the type error go away is to add an explicit initializer to the username
property. This way, the property holds a string value right away and is not observably undefined
:
class User {
username = "n/a";
}
const user = new User();
// OK
const username = user.username.toLowerCase();
#Solution #3: Assignment in the Constructor
Perhaps the most useful solution is to add a username
parameter to the constructor, which is then assigned to the username
property. This way, whenever an instance of the User
class is constructed, the caller has to provide the username as an argument:
class User {
username: string;
constructor(username: string) {
this.username = username;
}
}
const user = new User("mariusschulz");
// OK
const username = user.username.toLowerCase();
We could simplify the User
class by removing the explicit assignment to the class field and adding the public
modifier to the username
constructor parameter:
class User {
constructor(public username: string) {}
}
const user = new User("mariusschulz");
// OK
const username = user.username.toLowerCase();
Note that strict property initialization requires each property to be definitely assigned in all possible code paths in the constructor. The following (contrived) example is therefore not type-correct because in some cases, we leave the username
property uninitialized:
class User {
// Type error: Property 'username' has no initializer
// and is not definitely assigned in the constructor.
username: string;
constructor(username: string) {
if (Math.random() < 0.5) {
this.username = username;
}
}
}
#Solution #4: Definite Assignment Assertion
If a class property neither has an explicit initializer nor a type including undefined
, the type checker requires that property to be initialized directly within the constructor; otherwise, strict property initialization checks will fail. This is problematic if you want to initialize a property within a helper method or have a dependency injection framework initialize it for you. In these cases, you have to add a definite assignment assertion (!
) to that property's declaration:
class User {
username!: string;
constructor(username: string) {
this.initialize(username);
}
private initialize(username: string) {
this.username = username;
}
}
const user = new User("mariusschulz");
// OK
const username = user.username.toLowerCase();
By adding a definite assignment assertion to the username
property, we're telling the type checker that it can expect the username
property to be initialized, even if it cannot detect that on its own. It is now our responsibility to make sure the property is definitely assigned to after the constructor returns, so we have to careful; otherwise, the username
property can be observably undefined
and we're back to the TypeError
at runtime.
This article and 44 others are part of the TypeScript Evolution series. Have a look!