Use optional chaining (?.), nullish coalescing (??), type narrowing with conditionals, and strict null checks to handle nullable values safely.
TypeScript's strict null checking (part of strict mode) treats null and undefined as distinct types, forcing you to handle them explicitly.
Optional chaining (?.) safely accesses nested properties that might not exist: user?.address?.city returns undefined instead of throwing if any part is null/undefined. Great for accessing data from APIs where structure isn't guaranteed.
Nullish coalescing (??) provides defaults for null/undefined specifically: const name = user.name ?? 'Anonymous'. Unlike ||, it doesn't treat empty strings or 0 as falsy, only null and undefined.
Type narrowing uses control flow to refine types. After an if (user !== null) check, TypeScript knows user is defined in that block. The typeof, instanceof, and in operators also narrow types.
Non-null assertion (!) tells TypeScript you're certain a value isn't null: user!.name. Use sparingly—it bypasses safety checks. Better to narrow types or handle the null case.
For function parameters, make nullability explicit in types: function greet(name: string | null). This documents the contract and forces callers to handle the possibility. Default parameters (name = 'friend') can simplify null handling at function boundaries.
Use optional chaining (?.), nullish coalescing (??), type narrowing with conditionals, and strict null checks to handle nullable values safely.
Join our network of elite AI-native engineers.