TypeScript error: Object is possibly 'undefined' after I already checked it
asked 2 months ago157 viewsen
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.
1 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.
Sign in and verify your email to post an answer.