1

I have this code, but i get an error on this code underlined 'startups[i].logo' is possible undefined, why this error if I use if to check the values ?

  for (let i = 0; i < startups.length; i++) {
    let startup = startups[i];
    if (startups[i] && startups[i].logo && startups[i].logo.location) {
      aStartup.push({
        objectID: startups[i].id,
        logo: startups[i].logo.location,
      });
      batchCount ++;
    }
5
  • What is the type of startups? Commented Dec 20, 2018 at 22:26
  • At which stage of the transpilation does the error happens? Commented Dec 20, 2018 at 22:26
  • startups comes from a select , i've updated the question Commented Dec 20, 2018 at 22:42
  • webstorm alert show the error, and when webstomr show error then the compile will give error too Commented Dec 20, 2018 at 22:42
  • Then i think you'll find this answer useful. Commented Dec 20, 2018 at 23:12

1 Answer 1

1

Extract the nullable parts to local variables:

for (let i = 0; i < startups.length; i++) {
  const startup = startups[i];
  const logo = startup.logo;

  if (startup && logo && logo.location) {
    aStartup.push({
      objectID: startup.id,
      logo: logo.location
    });

    batchCount ++;
  }
}

This makes a difference because TypeScript knows all nullable scenarios have been eliminated within this block.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.