TypeScript error: Object is possibly 'undefined' after I already checked it

asked 2 months ago157 viewsen

7
const user = users.find(u => u.id === id);
if (user) {
  setTimeout(() => {
    console.log(user.name);
  });
}
const cfg = map.get('x');
if (map.has('x')) cfg.value; // error: possibly undefined

Why doesn't TS understand my checks?

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked 2 months ago

1 Answer

5
✓
✓ Accepted answer

Two different situations:

1. The user example actually works. Narrowing a const carries into closures. If you see an error there, user is probably declared with let: TS can't prove it wasn't reassigned before the callback runs. Use const.

2. map.has('x') does not narrow map.get('x'). TypeScript doesn't link the two calls. Check the value itself:

const cfg = map.get('x');
if (cfg !== undefined) {
  cfg.value; // ok
}

Avoid cfg!.value (the non-null assertion) unless you're truly certain. It silences the compiler without adding a runtime check.

Sign in to tell others whether this worked.

answered 2 months ago

Sign in and verify your email to post an answer.