Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected "Object is possibly 'undefined'." error with a nullable key #54854

Closed
alex996 opened this issue Jul 1, 2023 · 2 comments
Closed

Comments

@alex996
Copy link

alex996 commented Jul 1, 2023

Bug Report

🔎 Search Terms

Object is possibly 'undefined' / undefined key / nullable key

🕗 Version & Regression Information

  • This is the behavior in every major version I tried, from 3 to 5, and I reviewed the FAQ for entries matching "undefined", "object", "record", and "property".

⏯ Playground Link

Playground link with relevant code (Nightly)

💻 Code

const food: Record<string, string[] | undefined> = {"fruits": ["apple"]};

const keys = ["vegetables", "meat", "dairy", undefined];
const randomKey = keys[Math.floor(Math.random() * keys.length)];

if (randomKey) {
    if (food[randomKey]) {
        food[randomKey].push("whatever")
    } else {
        food[randomKey] = ["whatever"];
    }
}

🙁 Actual behavior

It fails to compile with an error: Object is possibly 'undefined'.(2532).

It should compile because:

  1. We check that randomKey is truthy (I tried if (randomKey !== undefined) { but got the same error)
  2. We check that food[randomKey] is truthy (I tried if (food[randomKey] !== undefined) { but got the same error)
  3. The resulting JavaScript code executes without a runtime error.

🙂 Expected behavior

It should compile without errors.

@MartinJohns
Copy link
Contributor

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.

@alex996
Copy link
Author

alex996 commented Jul 1, 2023

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"];
    }
}

@alex996 alex996 closed this as completed Jul 1, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants