Sub topic 8
strictNullChecks: handling null and undefined
This chapter assumes you can read basic TypeScript (annotations, unions, functions) and that you know what "strict": true does in tsconfig.json. It covers one flag from that group, strictNullChecks, and the code patterns it requires.
What the flag changes
With strictNullChecks off, null and undefined belong to every type. A variable typed string can hold null, and the compiler never complains. That hides the most common runtime error in JavaScript: Cannot read properties of null.
With the flag on, null and undefined are separate types. A value can be null only if its type says so, for example string | null. The compiler then requires you to handle the empty case before you use the value.
The flag is part of strict. You can switch it off alone with "strictNullChecks": false, but that is a temporary migration step, not a goal.
The basic error and its fix
function lengthOf(text: string | null): number {
return text.length;
}
function safeLengthOf(text: string | null): number {
return text === null ? 0 : text.length;
}The first function fails with 'text' is possibly 'null' (error TS18047). For undefined the message reads 'text' is possibly 'undefined' (TS18048). In the second function, the check text === null narrows the type. Narrowing means the compiler tracks which checks you have made and shrinks the union in each branch. After the check, text is string in the false branch.
Ways to narrow
Several constructs narrow null and undefined. Pick the one that matches your intent.
| Technique | Example | Watch out for |
|---|---|---|
| Strict comparison | `x === null`, `x !== undefined` | Checks one of the two values only. |
| Loose comparison | `x == null` | Matches both `null` and `undefined`. |
| Truthiness | `if (x) { ... }` | Also rejects `0`, `""`, and `false`. |
| Optional chaining | `user?.address?.city` | Result type includes `undefined`. |
| Nullish coalescing | `x ?? "default"` | Replaces only `null` and `undefined`. |
| Early return | `if (x === null) return;` | Narrows the rest of the function. |
The following example shows several of these together.
interface Profile {
name: string;
nickname?: string | null;
address?: { city: string };
}
function displayName(profile: Profile): string {
return profile.nickname ?? profile.name;
}
function cityOf(profile: Profile): string {
return profile.address?.city ?? "unknown";
}
console.log(displayName({ name: "Ada", nickname: null }));
console.log(cityOf({ name: "Ada" }));The first call prints Ada. The second prints unknown.
Prefer ?? over ||
A common bug is using || for defaults. It treats 0 and "" as missing.
function pageSize(requested: number | undefined): number {
return requested ?? 20;
}
console.log(pageSize(0));
console.log(pageSize(undefined));This prints 0 and then 20. With requested || 20, a requested size of 0 would silently become 20. The same applies to truthiness checks: if (count) is false when count is 0, even though 0 is a valid number.
Optional properties and parameters
A property declared email?: string has type string | undefined. A parameter declared limit?: number is also number | undefined inside the function. Both must be handled before use.
Do not confuse "optional" with "nullable". email?: string means the key may be missing. email: string | null means the key must be present but may hold null. APIs often return the second form in JSON, so type it as you receive it.
Where null and undefined come from
The flag makes you deal with empty values that standard library functions already produce.
const prices = new Map<string, number>([["apple", 3]]);
const price = prices.get("pear");
const total = (price ?? 0) * 2;
const names = ["Ada", "Grace"];
const found = names.find((name) => name.startsWith("G"));
console.log(total, found?.toUpperCase());Here Map.get returns number | undefined, and Array.find returns string | undefined. Other common sources include RegExp.exec and String.match (both return null on no match), document.querySelector, and values read from JSON.parse after you assert a type.
Filtering empty values out of arrays
filter(Boolean) does not change the element type in a way the compiler can see. Write a type guard instead. A type guard is a function whose return type, value is T, tells the compiler what a true result means.
function isPresent<T>(value: T | null | undefined): value is T {
return value !== null && value !== undefined;
}
const raw: (string | null)[] = ["a", null, "b"];
const clean: string[] = raw.filter(isPresent);
console.log(clean.join(","));This prints a,b, and clean has the type string[] without a cast.
The non-null assertion and its risks
The postfix ! operator tells the compiler to treat a value as non-null.
const prices = new Map<string, number>([["apple", 3]]);
const apple = prices.get("apple")!;
console.log(apple + 1);This compiles, but ! is erased at build time and adds no runtime check. If the key were missing, apple would be undefined and apple + 1 would give NaN, with no error to point at the cause. Use ! only when something the compiler cannot see guarantees the value, and prefer an explicit check that throws a clear message:
function mustGet<K, V>(map: Map<K, V>, key: K): V {
const value = map.get(key);
if (value === undefined) {
throw new Error(`Missing key: ${String(key)}`);
}
return value;
}Common errors and what they mean
Type 'null' is not assignable to type 'string': you assignednullto a variable that does not allow it. Either widen the type tostring | nullor fix the value.'x' is possibly 'undefined': you used a value before checking it. Add a check, a default with??, or optional chaining.Type 'string | undefined' is not assignable to type 'string': you passed an optional value to a function that needs a definite one. Narrow first, or change the function's parameter type ifundefinedis acceptable there.Variable 'x' is used before being assigned: aletwithout an initializer is read on a path where it was never set. Initialize it or restructure the branches.
Design advice
- Keep the nullable part of a type near the edges of your program. Validate input once, then pass definite types inward.
- Choose one empty value per concept. Mixing
nullandundefinedfor the same field forces every caller to handle both. - Return a default or throw at the boundary instead of passing
T | undefinedthrough many layers.
Exercise
Why does function f(count: number | undefined): number { return count || 10; } behave differently from count ?? 10 when count is 0, and which one is correct if 0 is a valid count?
Show answer
count || 10 replaces every falsy value, including 0, so it returns 10 for 0. count ?? 10 replaces only null and undefined, so it returns 0. If 0 is a valid count, ?? is correct.
Exercise
With strictNullChecks on, const first = names.find((n) => n.length > 3); return first.toUpperCase(); fails to compile. Give two different fixes.
Show answer
Array.find returns string | undefined. One fix is optional chaining with a default: return first?.toUpperCase() ?? "";. Another is an explicit check: if (first === undefined) { throw new Error("No match"); } return first.toUpperCase();.