// 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');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: 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.