Bugs

TypeScript Null and Undefined: How strictNullChecks Helps

With strictNullChecks enabled, TypeScript requires you to handle null and undefined before using them — eliminating an entire class of runtime errors.


❌ Unchecked Nullable Access

function getUserEmail(userId: string): string {
  const user = db.findUser(userId);  // Returns User | null
  return user.email;  // TypeScript error! Object is possibly null
}

✅ Fixed with Null Guard

function getUserEmail(userId: string): string {
  const user = db.findUser(userId);
  if (user === null) {
    throw new Error(`User ${userId} not found`);
  }
  return user.email;  // Now TypeScript knows user is User
}
💡

Pro tip: The ! operator asserts non-null but should be used sparingly and only when you're certain. Overusing ! disables safety just like any.

Paste this code into LearnCodeGuide

Detect TypeScript vulnerabilities and bugs automatically with AI-powered analysis.

Analyze TypeScript Code →

Related Guides

Typescript Type ErrorsTypescript Any Type AbuseJavascript Undefined Errors