【发布时间】:2019-12-09 08:44:21
【问题描述】:
我在打字稿文件中有一个函数,一切正常,除了即使在 if 检查之后仍然存在:“对象可能是'未定义'”。
我在其他文件中有类似的代码片段,但它们都没有给我同样的问题。
功能:
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) 消除对象未定义的可能性,但它没有这样做。
【问题讨论】:
标签: javascript reactjs graphql apollo