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
- Enable
strictNullChecksin tsconfig.json. - Use optional chaining:
const street = user?.address?.street; - Provide defaults with nullish coalescing:
const name = input ?? 'Guest'; - Narrow types with
if (value != null)checks. - Use the non-null assertion operator
!sparingly when you are certain a value exists.
Tips
??only falls back onnullorundefined, unlike||which also treats0and '' as falsy.- Defensive coding with early returns reduces nested null checks and improves readability.
Common issues
- Disabling
strictNullChecksallowsnullto 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.