Sub topic 8
null, undefined, and strictNullChecks
This chapter assumes you know basic JavaScript, can run code with tsc or an editor that reports TypeScript errors, and have read the earlier chapters on primitives, inference, and literal types. By the end you should know what strictNullChecks changes, how to handle values that might be missing, and which operators and patterns cause trouble.
Two empty values in JavaScript
JavaScript has two values that mean "nothing here":
undefinedis what the language gives you when a value was never set. An uninitialized variable, a missing object property, a function with noreturn, and a skipped argument all produce it.nullis a value you assign on purpose to say "there is intentionally no value".
In TypeScript each one is also a type. The type undefined has one value, undefined. The type null has one value, null. They are separate types, and they are not the same as 0, "", or false.
let a: undefined = undefined;
let b: null = null;
const user = { name: "Ada" };
const missing = (user as { name: string; age?: number }).age; // undefined at runtime
console.log(a, b, missing);What strictNullChecks changes
The compiler option strictNullChecks controls whether null and undefined belong to every type.
- When it is off,
nullandundefinedcan be assigned to any type. Astringvariable may holdnull, and the compiler says nothing. - When it is on,
nullandundefinedare only assignable to their own types (and toany,unknown, and unions that list them). Astringis always a string.
Turning it on moves a whole class of runtime crashes, such as Cannot read properties of undefined, to compile time.
{
"compilerOptions": {
"strict": true
}
}strict: true enables strictNullChecks along with several other checks. You can also set "strictNullChecks": true by itself. New projects created with tsc --init have strict on. The examples below assume it is on.
let title: string = "Intro";
// title = null; // Error: Type 'null' is not assignable to type 'string'.
// title = undefined; // Error: Type 'undefined' is not assignable to type 'string'.
let maybeTitle: string | null = "Intro";
maybeTitle = null; // ok, the type says null is allowedA union such as string | null is how you tell the compiler that a value may be missing. The type now documents the possibility, and the compiler forces every caller to deal with it.
Where missing values come from
Once the option is on, you will see | undefined and | null appear in several places without writing them yourself.
| Source | Resulting type | Column |
|---|---|---|
| Optional property `age?: number` | `number \ | undefined` |
| Optional parameter `(x?: string)` | `string \ | undefined` |
| `array.find(...)` | `T \ | undefined` |
| `map.get(key)` | `V \ | undefined` |
| `document.getElementById(id)` | `HTMLElement \ | null` |
| `string.match(regex)` | `RegExpMatchArray \ | null` |
| Function with no `return` on some path | return type includes `undefined` |
Each of these is a real case where JavaScript can hand you nothing, so the type tells the truth.
const names = ["Ada", "Grace", "Linus"];
const found = names.find((n) => n.startsWith("G")); // string | undefined
// console.log(found.length); // Error: 'found' is possibly 'undefined'.Handling a possibly missing value
The compiler error "possibly undefined" is asking you to check. Every check you make narrows the type, as covered in the narrowing chapter. These are the common forms.
Equality checks
function lengthOf(text: string | null): number {
if (text === null) {
return 0;
}
return text.length; // text is string here
}Truthiness checks
function shout(text?: string): string {
if (!text) {
return "";
}
return text.toUpperCase(); // text is string here
}Truthiness is a blunt tool. It removes null and undefined, but it also removes "", 0, NaN, and false. If 0 or an empty string is a valid value, use an explicit comparison instead.
function formatCount(count: number | undefined): string {
if (count === undefined) {
return "unknown";
}
return `${count} items`; // 0 is handled correctly: "0 items"
}Loose equality with null
value == null is true for both null and undefined. Many style guides ban ==, but this one use is common and TypeScript narrows it correctly.
function trimOrEmpty(value: string | null | undefined): string {
if (value == null) {
return "";
}
return value.trim(); // string
}Optional chaining and nullish coalescing
Two operators shorten these checks.
a?.breturnsundefinedifaisnullorundefined. Otherwise it readsb.a ?? breturnsbonly ifaisnullorundefined. Otherwise it returnsa.
type Profile = { address?: { city?: string } };
function cityOf(profile: Profile | undefined): string {
return profile?.address?.city ?? "Unknown";
}
console.log(cityOf(undefined)); // Unknown
console.log(cityOf({ address: { city: "Lagos" } })); // LagosPrefer ?? over || for defaults. The || operator replaces every falsy value, so 0 || 10 is 10, which is usually a bug. 0 ?? 10 is 0.
const port = 0;
console.log(port || 3000); // 3000, replaces a valid 0
console.log(port ?? 3000); // 0Optional properties versus properties that allow undefined
These two declarations look similar but differ.
type A = { nickname?: string }; // property may be absent
type B = { nickname: string | undefined }; // property must be present
const a: A = {}; // ok
// const b: B = {}; // Error: Property 'nickname' is missing.
const b: B = { nickname: undefined }; // okUse ? when the key can be left out. Use | undefined when the key must always exist but its value may be empty. A compiler option called exactOptionalPropertyTypes goes further and forbids writing nickname: undefined for an optional property. It is not part of strict and is rarely needed at this level.
The non-null assertion operator
A postfix ! tells the compiler "this is not null or undefined". It removes the checks from the type without adding any check to the running code.
const input = document.getElementById("email")!; // type: HTMLElementIf the element does not exist, input is null at runtime, and the next property access throws. The compiler cannot catch this because you told it not to look.
A safer version of the same code:
function requireElement(id: string): HTMLElement {
const element = document.getElementById(id);
if (element === null) {
throw new Error(`Missing element with id "${id}"`);
}
return element; // narrowed to HTMLElement
}Narrowing does not always survive
Narrowing applies within a stretch of code where the compiler can see the value does not change. Two situations commonly lose it.
- Callbacks. Narrowing a
letvariable is not trusted inside a function that runs later, because the variable could change before the callback runs. Aconstkeeps its narrowing. - Mutable properties. A check on
obj.propmay not hold after a function call, but TypeScript is lenient here and generally keeps the narrowing. Copy the property to aconstwhen you want to be safe.
function schedule(label: string | undefined) {
if (label === undefined) {
return;
}
const safeLabel = label; // const copy, type string
setTimeout(() => {
console.log(safeLabel.toUpperCase());
}, 100);
}Definite assignment
With strict on, a variable that is read before it is certainly assigned is an error.
let total: number;
// console.log(total); // Error: Variable 'total' is used before being assigned.
total = 5;
console.log(total); // okClass properties get a similar check under strictPropertyInitialization, which requires a property typed without undefined to be set in the constructor or have an initializer.
Common errors
| Symptom | Cause | Fix | Column | Column |
|---|---|---|---|---|
| `Object is possibly 'undefined'` | Value from `find`, `get`, or an optional field used directly | Check, use `?.`, or give a default with `??` | ||
| `Type 'null' is not assignable to type 'string'` | `strictNullChecks` is on and the type does not list `null` | Widen to `string \ | null` or stop returning `null` | |
| Default replaced a valid `0` or `""` | Used `\ | \ | ` for defaults | Use `??` |
| Crash on a value the compiler accepted | Used `!` on something that was actually missing | Replace with a real check | ||
| Array index returns a value typed as non-undefined | `arr[5]` has type `T` unless `noUncheckedIndexedAccess` is on | Check the result, or enable that option |
A worked example
This function combines the pieces from this chapter. It reads a nested optional value, handles a lookup that can fail, and keeps 0 as a valid result.
type Settings = {
retries?: number;
server?: { host?: string };
};
const registry = new Map<string, Settings>();
registry.set("prod", { retries: 0, server: { host: "example.com" } });
function describeSettings(name: string): string {
const settings = registry.get(name); // Settings | undefined
if (settings === undefined) {
return `${name}: not configured`;
}
const retries = settings.retries ?? 3;
const host = settings.server?.host ?? "localhost";
return `${name}: ${host}, retries=${retries}`;
}
console.log(describeSettings("prod")); // prod: example.com, retries=0
console.log(describeSettings("dev")); // dev: not configuredExercise
A function has the signature function pick(count: number | undefined): number and uses return count || 10;. What does pick(0) return, why is that likely a bug, and how do you fix it?
Show answer
It returns 10. The || operator replaces every falsy value, and 0 is falsy, so a valid count of 0 is thrown away. Replace it with return count ?? 10;, which only supplies the default when count is null or undefined.
Exercise
With strictNullChecks on, const el = document.getElementById("app"); followed by el.textContent = "Hi"; fails to compile. Give two ways to fix it, and say which is safer.
Show answer
The error occurs because el has type HTMLElement | null. One fix is a non-null assertion: el!.textContent = "Hi";. The other is a check: if (el !== null) { el.textContent = "Hi"; } (or throw an error when it is null). The check is safer because it runs at runtime. The ! only silences the compiler and crashes if the element is missing.