简体   繁体   中英

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.

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 Country | undefined . Here the undefined case has to be handled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM