Handling Unexpected Null Values in TypeScript: Best Practices for Edge Cases

Learn how to handle unexpected null values in TypeScript with beginner-friendly tips and best practices to write safer and more reliable code.

When working with TypeScript, one common challenge developers face is handling unexpected null values. Although TypeScript's strict null checks help reduce bugs, null values can still appear due to runtime data or external APIs. In this article, we will explore practical ways to handle null values gracefully and avoid common pitfalls.

First, it’s important to understand what null values are. In JavaScript and TypeScript, null represents an intentional absence of any object value. Unlike undefined, which means a variable has not been assigned a value, null is usually set deliberately.

### Use TypeScript's Union Types to Declare Nullable Variables

You can explicitly declare when a variable can be null by using union types. For example, if you have a user object that might be null, define its type as `User | null`.

typescript
type User = {
  name: string;
  age: number;
};

let currentUser: User | null = null;

// Later in code
currentUser = { name: "Alice", age: 30 };

### Use Conditional Checks Before Accessing Properties

Before accessing properties or methods on a potentially null object, always check if it is not null to avoid runtime errors.

typescript
if (currentUser !== null) {
  console.log(currentUser.name);
} else {
  console.log("User is not available");
}

### Leverage Optional Chaining for Cleaner Code

TypeScript's optional chaining operator (`?.`) lets you safely access nested properties even when an intermediate object might be null or undefined.

typescript
console.log(currentUser?.name); // Prints 'Alice' or undefined if currentUser is null

### Use Nullish Coalescing to Provide Defaults

Sometimes, you want to provide a fallback value if the variable is null or undefined. Use the nullish coalescing operator (`??`) to handle this correctly.

typescript
const displayName = currentUser?.name ?? "Guest";
console.log(displayName); // Prints 'Alice' or 'Guest'

### Handle Nulls in Function Parameters

When a function parameter can be null, specify its type accordingly and guard your code against null inputs.

typescript
function greetUser(user: User | null) {
  if (user === null) {
    console.log("Hello, Guest!");
  } else {
    console.log(`Hello, ${user.name}!`);
  }
}

### Summary

Handling unexpected null values in TypeScript becomes easier when you explicitly declare nullable types, use conditional checks, and leverage modern language features like optional chaining and nullish coalescing. By following these best practices, you can write more robust and error-resistant applications.