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

posée 2 months ago161 vuesen

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?

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 2 months ago

1 réponse

5
✓
✓ Réponse acceptée

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.

Connectez-vous pour dire si ça a marché.

answered 2 months ago

Sign in and verify your email to post an answer.