Sub topic 2
What strictNullChecks changes
This chapter assumes you know basic TypeScript types, union types, and the difference between null and undefined in JavaScript, and that you can edit a tsconfig.json. By the end you will know what the strictNullChecks option does to the type system, how to read the errors it produces, and what it does not change.
The rule it changes
Every type has a set of values. With strictNullChecks off, null and undefined belong to the set of every type. The type string means "any string, or null, or undefined". The compiler lets you assign them anywhere and call methods on any value without checking.
With strictNullChecks on, null and undefined become separate types with one value each. They no longer belong to string, number, object types, or any other type. If a value can be missing, its type must say so.
This is why the option catches a whole class of runtime crashes. The error TypeError: Cannot read properties of undefined happens when code treats a missing value as a present one. With the option off, the compiler cannot tell the two apart. With it on, it can.
Turning the option on
You can enable the option alone, or through the strict umbrella option:
{
"compilerOptions": {
"strict": true
}
}strict turns on a family of checks, including strictNullChecks, noImplicitAny, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitThis, alwaysStrict, and useUnknownInCatchVariables. You can switch one member off while keeping the rest. This is a common step in a migration:
{
"compilerOptions": {
"strict": true,
"strictNullChecks": false
}
}An explicit setting for an individual option wins over strict, whatever the order in the file.
Some options depend on this one. strictPropertyInitialization cannot be enabled without strictNullChecks, and the compiler reports error TS5052 if you try. The reason is that "this property may not have been assigned yet" only makes sense if undefined is a separate type.
Reading the first errors
The simplest effect is that null is no longer assignable to other types:
let name: string = "Ada";
// name = null; // Error with strictNullChecks: Type 'null' is not assignable to type 'string'.
let maybeName: string | null = null;
maybeName = "Ada";A variable that may hold null needs a union type such as string | null. The next chapter covers writing these types in detail. For now, treat the union as the compiler's way of recording that the value may be missing.
The second common effect shows up when you use a value that may be missing. Many standard library functions return such values. String.prototype.match returns RegExpMatchArray | null:
const match = "order-42".match(/\d+/);
console.log(match[0]); // error TS18047: 'match' is possibly 'null'.The compiler is right. If the string had contained no digits, match would be null and match[0] would throw at runtime. To fix it, check first:
const match = "order-42".match(/\d+/);
if (match !== null) {
console.log(match[0]); // match is RegExpMatchArray here
}The check works because of narrowing: inside the if, the compiler knows null has been ruled out. Narrowing gets its own chapter, so this is only a preview.
The third common effect appears in functions that return nothing in some paths:
function firstEven(nums: number[]): number {
for (const n of nums) {
if (n % 2 === 0) {
return n;
}
}
return undefined; // error TS2322: Type 'undefined' is not assignable to type 'number'.
}The function's signature promised a number, but one path returns undefined. The fix is to make the signature honest by changing the return type to number | undefined. Every caller then has to deal with the missing case.
Common error messages
These are the messages you will see most often. The numeric codes are stable across versions, and older compilers (before TypeScript 4.8 or so) word the "possibly" errors differently, as "Object is possibly 'null'" (TS2531) and "Object is possibly 'undefined'" (TS2532).
| Message | Code | Usual cause | Column |
|---|---|---|---|
| Type 'null' is not assignable to type 'string'. | TS2322 | Assigning `null` to a non-nullable variable or property | |
| Type 'string \ | undefined' is not assignable to type 'string'. | TS2322 | Assigning a possibly-missing value where a present one is required |
| 'x' is possibly 'null'. | TS18047 | Using a value that can be `null` without checking it | |
| 'x' is possibly 'undefined'. | TS18048 | Using a value that can be `undefined` without checking it | |
| Argument of type 'string \ | undefined' is not assignable to parameter of type 'string'. | TS2345 | Passing a possibly-missing value to a function that needs a present one |
| Property 'x' has no initializer and is not definitely assigned in the constructor. | TS2564 | A class property never assigned (needs `strictPropertyInitialization`) |
When you read one of these, find the variable named in the message and ask where the missing case comes from. The cause is almost always a function return type, an optional property, or an uninitialized variable. It is rarely the line the error points at.
What the option does not change
The option has limits, and some of them surprise people.
It does not change emitted JavaScript. The compiler checks types and then erases them. The same .js file comes out whether the option is on or off. Turning it on cannot change how your program behaves. It only changes which programs the compiler accepts.
It does not check data at runtime. If you declare const user: User = JSON.parse(text), the compiler trusts you. A null in the JSON where you declared string will still pass through. The type system only protects code paths it can see. The chapter on API boundaries returns to this.
It does not affect any. A value of type any accepts null and undefined, and you can also use an any value as if it were a string, number, or anything else. Using any switches the checks off for that value. Because of this, a codebase full of any gets little benefit from the option.
It does not affect unknown or void in the same way. unknown already accepts everything and forces you to narrow before use. void accepts undefined as its value, which is why a callback typed () => void can return nothing.
It does not make null or undefined illegal. You can still write let x: null = null or let y: undefined. The change is that these values are no longer implicitly part of every other type.
Effects on existing code
Turning the option on tends to produce errors in recognizable groups. Knowing the groups helps you plan the work.
- Lookups that can fail.
Map.get,Array.prototype.find,document.querySelector, andString.prototype.matchall return a type that includesnullorundefined. - Optional properties and parameters. A property declared
address?: Addresshas the typeAddress | undefined. Reading through it needs a check. - Uninitialized variables.
let result: string;followed by a read before assignment now produces an error: "Variable 'result' is used before being assigned." - Functions with early exits. A function that returns a value on some paths and
undefinedon others needs an honest return type. - Class properties. Properties assigned outside the constructor trigger TS2564 when
strictPropertyInitializationis on.
Each group has its own fix, and later chapters cover them in turn. The point here is that the errors are real findings, not noise. A typical codebase has a handful of actual bugs hidden among the first few hundred errors.
Checking the setting
If you are unsure whether a project has the option on, ask the compiler to print the resolved configuration:
npx tsc --showConfigThe output lists every option after extends chains and defaults are applied, so you can see whether strict or strictNullChecks is set and what value wins. This matters in monorepos, where a package may inherit from a shared base file that you did not open.
Exercise
A project has "strict": true in tsconfig.json, but a teammate adds "strictNullChecks": false below it. Does let s: string = null; compile, and does the compiled JavaScript differ from what it would be with the option on?
Show answer
Yes, it compiles, because an explicit strictNullChecks setting overrides the value implied by strict, and with the option off null is assignable to string. The compiled JavaScript is the same either way, because the option only affects type checking and types are erased at emit.
Exercise
The compiler reports "'match' is possibly 'null'" on console.log(match[0]), where match comes from "abc".match(/\d+/). Name the cause, and give one fix that keeps the program's behavior safe at runtime.
Show answer
String.prototype.match returns RegExpMatchArray | null, and it returns null when nothing matches (as with "abc" and \d+). Wrap the use in a check, for example if (match !== null) { console.log(match[0]); }. Inside the block the compiler narrows match to RegExpMatchArray, so the access is safe.