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 ++;
    }
DDave
  • 1,400
  • 3
  • 16
  • 33

1 Answers1

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.

Karol Majewski
  • 23,596
  • 8
  • 44
  • 53