Lesson

TypeScript Null & Undefined

10 min reading
Free Course

TypeScript Null and Undefined: Catching Missing Values Early

In JavaScript, undefined means a variable or property has not been assigned, while null represents an intentional empty value. When "strictNullChecks": true is enabled in tsconfig.json (part of "strict": true), TypeScript refuses to let you read properties on values that might be null or undefined.

That single compiler check wipes out the infamous "Cannot read properties of undefined" runtime bug before code ever ships.

Optional Chaining (?.) and Nullish Coalescing (??)

Use ?. to safely traverse nested properties that might be missing, and ?? to supply a fallback only when the left side is null or undefined (preserving 0, "", and false).

interface Profile {
  username: string;
  bio?: string | null;
  unreadCount?: number;
}

function summarizeProfile(profile: Profile | null): string {
  const name = profile?.username ?? "Guest";
  const count = profile?.unreadCount ?? 0; // Keeps 0 if unreadCount is 0!
  const bioText = profile?.bio?.trim() ?? "No bio provided";
  return `${name} (${count} unread) - ${bioText}`;
}

console.log(summarizeProfile({ username: "hana", unreadCount: 0 }));

Narrowing Before Using

Simple if (user !== null) checks, early return guards, and Array.isArray() automatically narrow away null and undefined in all lines below.

Common Mistakes to Avoid

  • Using || instead of ?? for numeric defaults: 0 || 10 evaluates to 10, overwriting a valid zero; 0 ?? 10 correctly preserves 0.
  • Overusing the ! non-null assertion (user!.name): Writing ! tells TypeScript to skip checking, re-introducing runtime crashes if assumptions change.
  • Turning off strictNullChecks: Without it, every string silently includes null | undefined and hides missing-data bugs.

Frequently Asked Questions

What is the difference between ?? and ||?

|| falls back on any falsy value (0, "", false, NaN, null, undefined). ?? falls back only on null and undefined.

How do I filter null and undefined out of an array cleanly?

Use a type predicate filter: items.filter((x): x is NonNullable<typeof x> => x != null) (in TypeScript 5.5+, .filter((x) => x !== null) infers this automatically!).

Should API schemas prefer undefined or null?

JSON payloads cannot store undefined, so JSON APIs typically use null for explicit empty fields and omit optional keys, while TypeScript function options use undefined (?).

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
TypeScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum