Skip to content

Null Safety

Rule

  • Runtime Error Prevention - null and undefined values are among the most common sources of runtime crashes. TypeScript's strict null checks catch these issues at compile time, preventing "Cannot read property of undefined" errors that plague JavaScript applications.
  • Improved Code Reliability - When the type system guarantees a value cannot be null, you can confidently use it without defensive checks everywhere. This leads to cleaner, more reliable code that behaves predictably.
  • Better API Contracts - Explicit null handling clarifies your function signatures and interfaces about what they expect and return. Other developers immediately know whether they need to handle null cases.
  • Enhanced Developer Experience - IDEs provide better autocomplete and error detection when null safety is enforced, catching potential issues before they reach production.

Integration

Enable null safety in tsconfig.json file :

tsconfig.json
{
  "compilerOptions": {
    "strict": true,
    "strictNullChecks": true
  }
}

Examples

🚨 DON’T

type User = {
    name?: string;
    avatar?: string;
};

const findUser = (id: string): User => {
    return users.find((u) => u.id === id);
};

const user = findUser("123") as User;
const userName = user!.name!;
const avatarUrl = user!.avatar!;

✅ DO

type User = {
    name: string;
    avatar?: string;
};

type Nullable<T> = T | null;

const findUser = (id: string): Nullable<User> => {
    return users.find((u) => u.id === id) || null;
};

const user = findUser("123");
if (user) {
    const userName = user.name;
    const avatarUrl = user.avatar ?? "/default-avatar.png";
}