Sub topic 2
What `strictNullChecks` changes
Assume you know basic TypeScript types, union types, interfaces, and how to use tsconfig.json. This chapter focuses on the compiler option that makes missing values visible in your types.
JavaScript has two common values for “no value”:
undefinedusually means a value was not provided or a property does not exist.nullusually means a program deliberately set a value to “nothing”.
They are different runtime values:
console.log(undefined === null); // false
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object"TypeScript can model this difference. The strictNullChecks option controls whether it does.
The behavior without strict null checks
When strictNullChecks is disabled, TypeScript treats null and undefined as assignable to many other types. A variable declared as string might still receive null.
That makes existing JavaScript code easier to accept, but the type does not describe the value accurately. Code can call a string method when the actual value is missing.
With strictNullChecks enabled, string, null, and undefined are separate types:
| Type | Values accepted | Column |
|---|---|---|
| `string` | String values only | |
| `null` | `null` only | |
| `undefined` | `undefined` only | |
| `string \ | null` | A string or `null` |
Enable the option directly or through the strict family of options:
{
"compilerOptions": {
"strict": true
}
}The strict setting enables strictNullChecks together with other strict checks. You can enable only this check when migrating an older project:
{
"compilerOptions": {
"strictNullChecks": true
}
}Reading the errors
Once the option is enabled, a type must include every value it can actually hold.
let name: string = "Ada";
// This would produce:
// Type 'null' is not assignable to type 'string'.
// name = null;
let maybeName: string | null = null;
maybeName = "Ada";The vertical bar creates a union type. string | null means that the variable may contain either a string or null.
The error is useful because it points to a decision the program must make. You can:
- provide a value that is always present;
- include
nullin the type; - check the value before using it;
- provide a default value;
- redesign the function so it cannot receive a missing value.
A compiler error is not saying that null is always wrong. It is saying that the current type and the current assignment disagree.
How the flag changes control flow
A nullable value cannot be used as though it were present. An early return or another check narrows the type. Narrowing means that TypeScript uses a condition to remove impossible types from a variable.
function shout(s: string | null | undefined): string {
if (s == null) {
return "";
}
return s.toUpperCase();
}The == null check is intentional here. It matches both null and undefined. After the return, TypeScript knows that s is a string.
You can also check the two values separately:
function lengthOf(s: string | null | undefined): number {
if (s === null || s === undefined) {
return 0;
}
return s.length;
}A truthiness check is shorter, but it also rejects valid values such as an empty string, 0, and false:
function displayName(name: string | undefined): string {
if (!name) {
return "Anonymous";
}
return name;
}Use a truthiness check only when every falsy value should receive the fallback. Use an explicit nullish check when an empty or zero value is meaningful.
What to expect in an existing project
Turning on the option can produce errors at:
- properties or parameters that may be absent;
- functions that return
undefinedon some paths; - DOM queries that may find no element;
Map.get, which returnsundefinedfor a missing key;- array or object lookups whose result may not exist.
Fix these errors at their source when possible. For example, a function that may fail should state that in its return type:
function findUser(id: string): { id: string } | undefined {
if (id === "ada") {
return { id: "ada" };
}
return undefined;
}Callers then have to handle the missing-user case instead of discovering it through a runtime exception.
Exercise
Why does let value: string = null fail when strictNullChecks is enabled, and what are two valid ways to fix the design?
Show answer
It fails because null is not part of the string type. Either make the type string | null and check it before use, or ensure the program supplies a string before assigning it.