Sub topic 11
Handle null and undefined
This chapter assumes you have a project with a working tsconfig.json, at least one file renamed to .ts, and a basic grasp of annotations and interfaces from earlier chapters. You should also know that JavaScript has two "no value" values: null and undefined.
Why null and undefined cause most runtime crashes
In plain JavaScript, any variable can hold null or undefined at any time. The engine only complains when you act on the missing value:
const names = ["Ada", "Grace"];
const hit = names.find((n) => n.startsWith("L"));
console.log(hit.toUpperCase()); // TypeError: Cannot read properties of undefinedTypeScript can catch this before the code runs, but only if you turn on the strictNullChecks option. It is part of strict, and it is the single flag that changes the most about how you write code.
What strictNullChecks changes
With strictNullChecks off, null and undefined are quietly allowed in every type. A string variable may hold null and the compiler says nothing. With it on, null and undefined become their own types. A string holds only strings, and you must say so when a value may be missing.
You can enable the flag alone, without turning on all of strict:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"rootDir": "src",
"outDir": "dist",
"allowJs": true,
"esModuleInterop": true,
"skipLibCheck": true,
"strict": false,
"strictNullChecks": true
},
"include": ["src"]
}Expect a burst of new errors the first time. Most of them point at real places where your JavaScript assumed a value existed.
Where missing values come from
Knowing the common sources helps you decide the right fix for each error.
| Source | Example | Type you get | Column |
|---|---|---|---|
| Lookup that can fail | `array.find(...)` | `T \ | undefined` |
| Map lookup | `map.get(key)` | `V \ | undefined` |
| DOM query | `document.querySelector(...)` | `Element \ | null` |
| Optional property | `email?: string` | `string \ | undefined` |
| Optional parameter | `function f(x?: number)` | `number \ | undefined` |
| Regex match | `"a".match(/b/)` | `RegExpMatchArray \ | null` |
| Function with no `return` on some path | `if (ok) return 1;` | `number \ | undefined` |
Each of these is a union type. A union such as User | undefined says the value is either a User or undefined, and the compiler makes you handle both cases before you use it as a User.
Reading a typical error
Take a function converted from JavaScript:
interface User {
name: string;
age: number;
}
function findUser(users: User[], name: string): User | undefined {
return users.find((u) => u.name === name);
}
const user = findUser([{ name: "Ada", age: 36 }], "Ada");
console.log(user.name.toUpperCase());With strictNullChecks on, the last line fails with 'user' is possibly 'undefined' (error TS18048). The compiler is correct. find returns undefined when nothing matches, and the original JavaScript would have crashed in that case.
When you annotate findUser, write the honest return type, User | undefined. Do not write User to silence callers. That hides the problem and moves the crash to a place the compiler can no longer see.
Fix 1: check before you use
The most common fix is a conditional check. Inside the if, the compiler narrows the type. Narrowing means the compiler works out a more specific type from the checks you wrote.
interface User {
name: string;
age: number;
}
function findUser(users: User[], name: string): User | undefined {
return users.find((u) => u.name === name);
}
const user = findUser([{ name: "Ada", age: 36 }], "Ada");
if (user) {
console.log(user.name.toUpperCase());
} else {
console.log("No such user");
}Inside the first branch user is a User. In the else branch it is undefined.
A truthiness check such as if (user) also rejects 0, "" and false. For objects this is fine. For numbers and strings it can be a bug. Compare against the missing values directly when zero or an empty string is a valid value:
function describePort(port: number | undefined): string {
if (port === undefined) {
return "no port configured";
}
return "port " + port; // port is a number here, including 0
}
console.log(describePort(0));
console.log(describePort(undefined));Using port == null (loose equality) tests for both null and undefined in one comparison. Many style guides forbid == elsewhere but allow this one case.
Fix 2: optional chaining
When a missing value should simply produce another missing value, use optional chaining (?.). It stops evaluating and returns undefined if the value on its left is null or undefined.
interface Profile {
name: string;
address?: {
city?: string;
};
}
function cityOf(profile: Profile): string | undefined {
return profile.address?.city;
}
console.log(cityOf({ name: "Ada" }));
console.log(cityOf({ name: "Ada", address: { city: "London" } }));The result type is still string | undefined. Optional chaining does not remove the missing case. It only defers it to the caller.
Fix 3: provide a default
Use the nullish coalescing operator (??) to supply a fallback. It substitutes the right side only when the left side is null or undefined.
function labelFor(name: string | undefined): string {
return name ?? "anonymous";
}
function retries(count: number | undefined): number {
return count ?? 3; // 0 is kept as 0
}
console.log(labelFor(undefined));
console.log(retries(0));Older JavaScript often used || for defaults. count || 3 turns 0 into 3, which is usually a bug. When you convert a file, check each || default and decide whether ?? is what the author meant.
Fix 4: fail early
If a missing value means the program is in a state it cannot recover from, throw. The throw also narrows the type for the code that follows.
function mustFind(users: { name: string }[], name: string): { name: string } {
const found = users.find((u) => u.name === name);
if (!found) {
throw new Error("User not found: " + name);
}
return found; // narrowed to a defined object
}
console.log(mustFind([{ name: "Ada" }], "Ada").name);The non-null assertion and why to ration it
The postfix ! operator tells the compiler a value is not missing:
const input = document.querySelector("#email")!;The compiler trusts you and removes null and undefined from the type. It adds no runtime check. If you are wrong, you get the same crash JavaScript would have given you. Use ! only when something the compiler cannot see guarantees the value, and prefer a check or a thrown error in most cases.
Optional versus nullable: choose one meaning
email?: string means the property may be absent. email: string | null means the property is always present but may hold null. They are different shapes, and JSON from an API often uses one while your JavaScript used the other loosely. Check what the data really looks like and model that. If both can occur, write email?: string | null.
Edge cases to know
- Callbacks lose narrowing. A check on a
letvariable does not carry into a function created later, because the variable could change in between. Copy the value into aconstafter checking. - Array indexing is not checked.
users[0]has typeUser, notUser | undefined, unless you enablenoUncheckedIndexedAccess. That option is a later, optional step. nullandundefinedare separate.string | undefineddoes not acceptnull. Converted code that compared with=== nullmay need== nullor an explicit union.- Class fields. A field with no initializer is reported when
strictPropertyInitializationis on, which is part ofstrict. Initialize it in the constructor or mark it optional.
A workflow for the error burst
Work through the errors one file at a time. Fix the type declarations first (optional properties, honest return types), because correcting a declaration often clears many errors downstream.
Exercise
This function compiles with strictNullChecks off. Rewrite it so it compiles with the flag on, returns 0 when the cart has no discount, and still treats a discount of 0 correctly. interface Cart { total: number; discount?: number } function finalPrice(cart: Cart): number { return cart.total - cart.discount; }
Show answer
Use ?? so that only a missing discount falls back, not a discount of 0: function finalPrice(cart: Cart): number { return cart.total - (cart.discount ?? 0); } cart.discount has type number | undefined, so subtracting it directly is an error. Writing cart.discount || 0 would also compile and give the same result here, but ?? states the intent and stays correct if the fallback is ever non-zero.
Exercise
A converted line reads const el = document.querySelector("#name") as HTMLInputElement; followed by el.value. Why can this still crash, and what is a safer version?
Show answer
querySelector returns Element | null, and the assertion does not check for null. If no element matches, el is null and el.value throws a TypeError. A safer version checks first: const el = document.querySelector("#name"); if (el instanceof HTMLInputElement) { console.log(el.value); } The instanceof check rejects null and narrows el to HTMLInputElement.