Closed alex996 closed 1 year ago
Duplicate of #10530. Type narrowing does not occur for indexed access forms e[k]
where k
is not a literal. Just store it in a local const
variable.
Apologies for the duplicate. I suspected it was going to be a long-standing issue.
If this a common enough problem, please consider adding it to the FAQ if it fits there.
Here's the fix as suggested (and with the playground)
if (randomKey) {
const arr = food[randomKey];
if (arr) {
arr.push("whatever")
} else {
food[randomKey] = ["whatever"];
}
}
Bug Report
🔎 Search Terms
Object is possibly 'undefined' / undefined key / nullable key
🕗 Version & Regression Information
⏯ Playground Link
Playground link with relevant code (Nightly)
💻 Code
🙁 Actual behavior
It fails to compile with an error:
Object is possibly 'undefined'.(2532)
.It should compile because:
randomKey
is truthy (I triedif (randomKey !== undefined) {
but got the same error)food[randomKey]
is truthy (I triedif (food[randomKey] !== undefined) {
but got the same error)🙂 Expected behavior
It should compile without errors.