Null Safety¶
Rule¶
- Runtime Error Prevention -
nullandundefinedvalues are among the most common sources of runtime crashes. TypeScript's strictnullchecks 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
nullhandling clarifies your function signatures and interfaces about what they expect and return. Other developers immediately know whether they need to handlenullcases. - Enhanced Developer Experience -
IDEs provide better autocomplete and error detection when
nullsafety is enforced, catching potential issues before they reach production.
Integration¶
Enable null safety in tsconfig.json file :
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";
}