Javascript “如何修复”;对象可能未定义";?
我在一个typescript文件中有一个函数,除了在进行if检查之后仍然有:“Object可能是‘未定义的’” 我在其他文件中有类似的代码段,但没有一个给我相同的问题 职能:Javascript “如何修复”;对象可能未定义";?,javascript,reactjs,graphql,apollo,Javascript,Reactjs,Graphql,Apollo,我在一个typescript文件中有一个函数,除了在进行if检查之后仍然有:“Object可能是‘未定义的’” 我在其他文件中有类似的代码段,但没有一个给我相同的问题 职能: renderCities = (countries: Country[], countryId: string) => { if (countryId === 'DEFAULT') { return <option>Select Country First</option>
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>
));
}
}
};
另一个类似代码:
<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>
{({错误,加载,数据})=>{
如果(装载){
返回装载。。。;
}else if(错误){
抛出新错误(“错误”);
}否则{
如果(数据){
回来
//过去,“数据国家”中也有同样的错误,但
//如果(数据)修复了它。
}
}
}}
我希望if(countries)可以取消对象未定义的可能性,但它没有这样做。如果(countries){…,您可以省略if子句 它是下一个可以不定义的表达式:
countries.find((country: Country) => country.id === parseInt(countryId))
,返回Country | undefined
。这里必须处理undefined
案例
countries.find((country: Country) => country.id === parseInt(countryId))