如何修复 "Object is possibly undefined"?

How to fix "Object is possibly undefined"?

我在打字稿文件中有一个函数,一切正常,除了即使在 if 检查之后仍然存在:"Object is possibly 'undefined'".

我在其他文件中有类似的代码片段,但其中 none 个给我同样的问题。

函数:

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>
          ));
      }
    }
  };

接口:

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

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

另一个类似的代码:

<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>

我希望 if (countries) 取消对象未定义的可能性,但它没有这样做。

您可以省略 if 子句 if (countries) { ...,没有必要。

下一个可以不定义的表达式:

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

,其中 returns Country | undefined。这里必须处理 undefined 案例。