如何修复searchCountry无返回值引发的TypeScript类型错误?
问题解决步骤
1. 修复Rest.getCountry的异步返回问题
当前getCountry是async函数,但内部未返回Axios请求的Promise链,导致它实际返回Promise<void>,无法传递正确的Country数据。同时注意代码里的拼写错误:captial应改为capital,确保和返回数据的结构匹配。
修改后的Rest代码:
import Axios from "axios"; // 先定义Country类型(如果项目中还未定义) export interface Country { capital: string[]; // restcountries API返回的capital是数组类型 continent: string[]; } const Rest = { async getCountry(nation: string): Promise<Country> { // 用await简化异步逻辑,避免嵌套then const response = await Axios.get(`https://restcountries.com/v3.1/name/${nation}`); const countryObject = { capital: response.data[0].capital, continent: response.data[0].continents, }; console.log(countryObject); return countryObject; }, }; export default Rest;
如果坚持使用then链式写法,必须返回Promise链:
async getCountry(nation: string): Promise<Country> { return Axios.get(`https://restcountries.com/v3.1/name/${nation}`).then( (response) => { const countryObject = { capital: response.data[0].capital, continent: response.data[0].continents, }; console.log(countryObject); return countryObject; } ); }
2. 修改SearchCountryProp接口
因为searchCountry是异步函数,实际返回的是Promise,所以接口里的返回类型要从void改为Promise<void>:
export interface SearchCountryProp { searchCountry: (country: string) => Promise<void>; }
3. 调整searchCountry函数实现
现在getCountry能正确返回Promise<Country>,searchCountry可以正常接收返回值并调用setCountryToSearch,同时保证函数返回Promise匹配接口类型:
// 确保countryState的类型是Country const [countryToSearch, setCountryToSearch] = useRecoilState<Country>(countryState); const searchCountry = async (country: string): Promise<void> => { const returnedCountry = await Rest.getCountry(country); setCountryToSearch(returnedCountry); };
或者用then链式写法:
const searchCountry = (country: string): Promise<void> => { return Rest.getCountry(country).then((returnedCountry) => { setCountryToSearch(returnedCountry); }); };
关键错误根源
Rest.getCountry作为async函数未返回异步操作结果,导致调用时拿到的是undefined,无法传递给setCountryToSearch;- 接口
SearchCountryProp中searchCountry的返回类型定义错误,异步函数必须返回Promise类型而非void; - 代码存在拼写错误
captial,会导致对象属性不匹配Country类型。
内容的提问来源于stack exchange,提问作者Michael Horvilleur
相关产品推荐
相关产品推荐

