Sub topic 8
null, undefined, and strictNullChecks
Prerequisites
This chapter assumes you can annotate functions, read a union type such as string | number, and edit a tsconfig.json file. You should also know that JavaScript has two "empty" values: null, which a program sets on purpose, and undefined, which appears when a value was never set.
Why the two values matter
In JavaScript, a missing value can surface anywhere. A lookup can fail, an optional field can be absent, and a function can return nothing. Without checks, the program crashes later with a message such as "cannot read properties of undefined."
TypeScript can catch these cases at compile time, but only when the compiler knows a value may be missing. The strictNullChecks option tells it to do so. Setting "strict": true in tsconfig.json turns this option on, along with several related checks.
{
"compilerOptions": {
"strict": true
}
}What strictNullChecks changes
With strictNullChecks off, null and undefined belong to every type. A string variable can silently hold null, so the compiler stays quiet. With it on, null and undefined belong only to their own types, and you must declare when a value can be missing.
function findUser(id: number): string | undefined {
return id === 1 ? "Ada" : undefined;
}
const name = findUser(2);
console.log(name.toUpperCase());
// Error: 'name' is possibly 'undefined'.The return type string | undefined tells every caller that a result may be missing. The compiler then rejects code that assumes a value is present.
Narrowing a nullable value
Narrowing means checking a value so the compiler knows its narrower type afterward. A !== undefined check narrows string | undefined to string inside the branch.
const name = findUser(2);
if (name !== undefined) {
console.log(name.toUpperCase()); // safe: name is string here
}The diagram below shows the decision path for a nullable value.
Optional chaining and fallbacks
Two operators shorten common checks. The optional chaining operator ?. returns undefined instead of throwing when the left side is missing. The nullish coalescing operator ?? supplies a default when the left side is null or undefined.
const greeting = findUser(2)?.toUpperCase() ?? "GUEST";
console.log(greeting); // "GUEST"Use ?? rather than || here. The || operator also replaces valid falsy values such as 0 and "", which often is not what you want.
Common errors
- Declaring a parameter as
stringwhen callers can passundefined. Widen the type tostring | undefinedor provide a default. - Using a non-null assertion (
value!) to silence the compiler. This tells the compiler to trust you, and it fails at runtime if you are wrong. - Relying on a truthiness check (
if (value)) when0or""are valid values.
Exercise
Exercise
Given function getPort(config: { port?: number }): number, return config.port when it is set and 8080 otherwise. Write the body in one line.
Show answer
return config.port ?? 8080;