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

poze 2 months ago155 gadeen

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?

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

poze 2 months ago

1 Repons

5
✓
✓ Repons yo aksepte

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.

Konekte pou di lòt moun si li te mache.

answered 2 months ago

Sign in and verify your email to post an answer.