簡體   English   中英

如何修復“對象可能未定義”?

[英]How to fix “Object is possibly undefined”?

我在打字稿文件中有一個函數,除了在進行if檢查后仍然存在:“對象可能是'undefined'”之外,其他所有東西都可以正常工作。

我在其他文件中有類似的代碼段,但是沒有一個給我同樣的問題。

功能:

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(國家/地區)可以消除對象未定義的可能性,但事實並非如此。

您可以省略if子句if (countries) { ... ,這不是必需的。

這是下一個無法定義的表達式:

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

,返回Country | undefined Country | undefined 在這種情況下,必須處理undefined情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM