eran helzer
eran helzer

Reputation: 155

How to fix "Object is possibly undefined"?

I have a function in a typescript file, everything works fine except that even after an if check there is still: "Object is possibly 'undefined'".

I have similar code pieces in other files but none of them give me the same problem.

The function:

renderCities = (countries: Country[], countryId: string) => {
    if (countryId === 'DEFAULT') {
      return <option>Select Country First</option>;
    } else {
      if (countries) {
        return countries //error here "Object is possibly 'undefined'"
          .find((country: Country) => country.id === parseInt(countryId))
          .cities.map((city: City) => (
            <option key={`city-${city.id}`} value={city.id}>
              {city.name}
            </option>
          ));
      }
    }
  };

The interfaces:

interface City {
  name: string;
  id: number;
}

interface Country {
  name: string;
  id: number;
  cities: City[];
}

Another similar code:

<Query<Data> query={GET_COUNTRIES_CITIES}>
        {({ error, loading, data }) => {
          if (loading) {
            return <h1>Loading...</h1>;
          } else if (error) {
            throw new Error('Error');
          } else {
            if (data) {
              return <TeacherForm countries={data.countries} />;
              //there used to be the same error in "data.countries", but the 
              //if (data) fixed it.
            }
          }
        }}
      </Query>

I expect the if (countries) to cancel out the possibility of the object being undefined, but it does not do so.

Upvotes: 1

Views: 974

Answers (1)

ford04
ford04

Reputation: 74510

You can leave out the if clause if (countries) { ..., it is not necessary.

It is the next expression which can be undefined:

countries.find((country: Country) => country.id === parseInt(countryId))

, which returns Country | undefined. Here the undefined case has to be handled.

Upvotes: 1

Related Questions