Null, undefined, and strict null checks
How `strictNullChecks` turns null and undefined into types you must handle, and how to model missing values with `T | null`, `?`, and `??`.
Primitive typesObject types, optional and readonly propertiesStrict mode and the compiler flags that matter
Null, undefined, and strict null checks
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Without `strictNullChecks`, `null` and `undefined` are allowed in every type, so the compiler cannot warn about the most common runtime crash; with it (part of `strict`), they are separate types you must include explicitly.
- A value that may be missing is typed as a union such as `User | undefined`, and the compiler refuses property access on it until you have checked it.
- `name?: string` means the property may be absent from the object; `name: string | undefined` means the property must be present but its value may be `undefined`.
- A common convention is `undefined` for 'not set or not found' and `null` for 'deliberately empty'; DOM APIs and JSON use `null`, while missing properties and array lookups give `undefined`.
- Optional chaining (`?.`) adds `undefined` to the result type, and `??` removes `null` and `undefined` from it by supplying a fallback.
- The non-null assertion `!` tells the compiler a value is not null without checking it; it is an escape hatch, not a fix.
The bug every JavaScript developer has shipped
Cannot read properties of undefined (reading 'name') is probably the most common runtime error in JavaScript. A lookup found nothing, a field was missing from an API response, an element wasn’t on the page, and code carried on as if the value were there. The JavaScript roadmap covers what null and undefined are at runtime. The question here is how a type checker can catch this crash before it happens.
What strictNullChecks changes
Without the strictNullChecks flag, TypeScript treats null and undefined as valid members of every type. A string might be null; a User might be undefined. The compiler has no way to separate “definitely a string” from “maybe a string”, so it can’t warn about the crash above.
With the flag on, which it is whenever strict is on, null and undefined become their own separate types. A string is only ever a string:
let title: string = "Dune";
title = null; // Error: Type 'null' is not assignable to type 'string'.
let subtitle: string | null = null; // fine: null is now stated
The | makes a union type: a value that may be either side. The union and literal types lesson covers unions properly; for now, read string | null as “a string, or null”.
The flag is part of the strict family covered in the strict mode lesson. It is the single most valuable one, and every example in this roadmap assumes it is on.
Missing values become visible
Once null and undefined are explicit, the standard library’s types tell the truth about functions that may come back empty:
type User = { id: number; name: string };
const users: User[] = [{ id: 1, name: "Ada" }];
const found = users.find((u) => u.id === 2); // User | undefined
found.name; // Error: 'found' is possibly 'undefined'.
if (found) {
found.name; // fine: checked
}
const heading = document.querySelector("h1"); // HTMLHeadingElement | null
heading.textContent = "Hi"; // Error: 'heading' is possibly 'null'.
Think of it as a delivery slip with a “not in stock” box. Without strict null checks, the slip has no such box, and you only discover the empty parcel when you open it. With them, every slip that could be empty says so, and you have to look before you unpack. The if (found) check is narrowing, which the narrowing group covers in full.
Optional ? versus | undefined
There are two ways to say a property might hold no value, and they’re not the same:
type A = { middleName?: string };
type B = { middleName: string | undefined };
const a: A = {}; // fine: the property may be absent
const b: B = {}; // Error: Property 'middleName' is missing in type '{}' but required in type 'B'.
const b2: B = { middleName: undefined }; // fine: present, value undefined
? is about whether the key exists. | undefined is about what the value may be, with the key still required. Use ? for genuinely optional fields; use | undefined when you want every caller to make an explicit decision. A separate flag, exactOptionalPropertyTypes, sharpens this further by forbidding middleName: undefined on type A; the strict mode lesson covers it.
null or undefined?
Both mean “no value”, and TypeScript lets you use either. A convention keeps code predictable:
undefinedfor “not set” or “not found”: missing properties, optional parameters,find,Map.get, array lookups beyond the end. JavaScript produces it on its own.nullfor “deliberately empty”: a field that was cleared, a selected item when nothing is selected. DOM APIs return it, and JSON can carrynullbut has noundefinedat all.
Many teams settle on undefined everywhere except at the DOM and JSON boundaries. Whichever you pick, put it in the type explicitly, and don’t mix both in one field without a reason.
?. and ?? through a type lens
Optional chaining and nullish coalescing are runtime features, but their effect on types is what makes them worth using here:
type Customer = { address?: { city?: string } };
function cityOf(c: Customer | undefined) {
const maybe = c?.address?.city; // string | undefined
const sure = c?.address?.city ?? "unknown"; // string
return sure;
}
?. stops at the first null or undefined and produces undefined, so its result type always gains | undefined. ?? supplies a fallback whenever the left side is null or undefined, so its result type loses both. Prefer ?? to || for defaults: || also replaces 0 and "", which are often legitimate values.
!, briefly
A postfix ! tells the compiler “trust me, this isn’t null”:
const root = document.getElementById("root")!; // HTMLElement
It performs no check. If the element is missing, the code crashes just as plain JavaScript would. Treat ! as a last resort; the assertions lesson covers when it’s defensible.
About the video
Angular University’s three-minute video shows the heart of the matter: what strictNullChecks does to null and undefined, and how the compiler starts reporting values that might be missing. Despite the channel name, nothing in it is Angular-specific. It is short, so the lesson text carries most of the weight here: the ? versus | undefined difference, the conventions for null and undefined, and how ?. and ?? change types are not covered in the video. Harry Wolff’s longer video in the links puts this flag in the context of the rest of strict.
Check yourself
With `strictNullChecks` off, why does `let name: string = null` compile?
With the flag off, `null` and `undefined` are treated as members of every type, so they can be assigned anywhere. That is precisely why the flag matters: the compiler then has no way to tell you that a `string` might be `null` when you call a method on it.
Why does `users.find((u) => u.id === id).name` fail under `strict`?
`find` returns `User | undefined`, because it may not find a match. Reading `.name` on a possibly `undefined` value would crash at runtime, so the compiler reports that the object is possibly `undefined`. Check the result first, or use `?.` and handle the `undefined` case.
What is the difference between `{ middleName?: string }` and `{ middleName: string | undefined }`?
With `?`, the object may leave the property out entirely. With `string | undefined`, the property must be written, even if its value is `undefined`, so `{}` is accepted by the first type but not the second.
What is the type of `user?.address?.city ?? "unknown"` if `city` is a `string`?
`string`. The optional chain on its own gives `string | undefined`, because any link in the chain could be missing. The `??` supplies a string whenever the left side is `null` or `undefined`, so the result can only ever be a string.
Why is `!` described as an escape hatch rather than a fix?
It removes `null` and `undefined` from the type without any runtime check. If you are wrong, the code crashes exactly as it would have in plain JavaScript, and the compiler can no longer warn you. A real check or a `??` fallback keeps the safety.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.