MediumType Errors🐛 Debug Challenge

Accessing property on potentially undefined value

Buggy Code — Can you spot the issue?

// TypeScript: Object is possibly 'undefined' — accessing .name on User | undefined
const users = [
  { id: 1, name: 'Alice', role: 'admin' },
  { id: 2, name: 'Bob',   role: 'user' },
  { id: 3, name: 'Carol', role: 'user' },
];

function getUserName(id) {
  const user = users.find(u => u.id === id);
  // Bug: user might be undefined if id not found
  // TypeScript error: 'user' is possibly 'undefined'
  return user.name; // silent wrong result when user is undefined
}

// Found user — works
console.log(getUserName(1));

// Not found — returns wrong result (should be a fallback, not crash)
console.log(getUserName(99) || 'Unknown');

Fixed Code

const users = [
  { id: 1, name: 'Alice', role: 'admin' },
  { id: 2, name: 'Bob',   role: 'user' },
  { id: 3, name: 'Carol', role: 'user' },
];

function getUserName(id) {
  const user = users.find(u => u.id === id);
  // Fix 1: null check with fallback
  if (!user) return 'Unknown';
  return user.name;

  // Fix 2: optional chaining + nullish coalescing (TypeScript idiomatic)
  // return users.find(u => u.id === id)?.name ?? 'Unknown';
}

console.log(getUserName(1));
console.log(getUserName(99));

Bug Explained

Bug: Array.find() returns T | undefined. Accessing .name without checking for undefined causes a runtime error when the item is not found. TypeScript flags this with strict null checks enabled.

Explanation: The null check guards against undefined before accessing .name. TypeScript with strict null checks would catch this at compile time, forcing you to handle the undefined case.

Key Insight: TypeScript strict null checks (strictNullChecks: true) surface these bugs at compile time. T | undefined from find() forces you to handle both cases. Use optional chaining (?.) and nullish coalescing (??) for concise null-safe code.

More Type Errors Debug Challenges

EasyWrong type assignment causes silent wrong outputMediumReturning wrong type from a function — silently truncates data

Practice spotting bugs live →

38 debug challenges with AI hints

🐛 Try Debug Lab