How to handle nullable types in TypeScript
· Category: TypeScript
Short answer
TypeScript nullable types use union syntax like string | null or string | undefined. Use optional chaining (?.), nullish coalescing (??), and type guards to safely access values that might be null. For type narrowing techniques, see how to use TypeScript generics.
Common patterns
// Optional chaining
const name = user?.profile?.name;
// Nullish coalescing
const value = input ?? "default";
// Type guard
function processValue(val: string | null) {
if (val !== null) {
// TypeScript knows val is string here
console.log(val.toUpperCase());
}
}
Strict null checks
Enable strictNullChecks in tsconfig.json to prevent implicit any-to-null conversions. This catches most null-related bugs at compile time.
Tips
- Use
!(non-null assertion) only when you are certain the value exists - Prefer explicit null checks over type assertions for safety