简体   繁体   English

如何修复“对象可能未定义”?

[英]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'". 我在打字稿文件中有一个函数,除了在进行if检查后仍然存在:“对象可能是'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. 我希望if(国家/地区)可以消除对象未定义的可能性,但事实并非如此。

You can leave out the if clause if (countries) { ... , it is not necessary. 您可以省略if子句if (countries) { ... ,这不是必需的。

It is the next expression which can be undefined: 这是下一个无法定义的表达式:

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

, which returns Country | undefined ,返回Country | undefined Country | undefined . Country | undefined Here the undefined case has to be handled. 在这种情况下,必须处理undefined情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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