How to handle null and undefined in TypeScript

· Category: TypeScript

Short answer

Enable strictNullChecks to catch null and undefined errors at compile time. Use optional chaining (?.) and nullish coalescing (??) for safe access and defaults.

Steps

  1. Enable strictNullChecks in tsconfig.json.
  2. Use optional chaining: const street = user?.address?.street;
  3. Provide defaults with nullish coalescing: const name = input ?? 'Guest';
  4. Narrow types with if (value != null) checks.
  5. Use the non-null assertion operator ! sparingly when you are certain a value exists.

Tips

  • ?? only falls back on null or undefined, unlike || which also treats 0 and '' as falsy.
  • Defensive coding with early returns reduces nested null checks and improves readability.

Common issues

  • Disabling strictNullChecks allows null to be assigned to any type, removing a major safety net.
  • The non-null assertion operator ! can mask bugs if your assumptions about initialization are wrong.