TypeScript报错:AxiosResponse与countries[]类型不匹配如何解决
报错原因
- 你调用
axios.get拿到的res是Axios封装的响应对象,里面包含状态码、响应头、响应数据等多类信息,并不是接口直接返回的国家数组,数组实际存放在res.data字段里,你直接把整个res赋值给声明为countries[]类型的countries状态,类型完全不匹配才会触发该报错。 - 你没有给
axios.get显式指定响应数据的类型,TS无法自动推导res.data的结构,需要通过泛型声明类型。
修正步骤
- 先修正现有类型定义的笔误:把
countries接口里的astring改为string,建议同时将接口名改为大驼峰Country(符合TS命名规范,避免和数组变量名混淆) - 给
axios.get添加泛型声明,指定响应返回的data类型为Country[] - 赋值时取
res.data而非整个res
修正后完整代码
export interface IProfileEditorState { countries: Country[]; error?: any; isLoading?: boolean; } // 接口名改为大驼峰更规范 interface Country { countryID: string; countryName: string; label: string; // 修正笔误astring为string value: string; isDirector: number; } // Temp public getCountrys() { axios // 泛型指定响应data的类型为Country[] .get<Country[]>('https://func-myportal-dev.azurewebsites.net/api/GetCountries?code=j0xGK8L6iRXpZqR3DgaDRoI/H/qjGZSGdBPIY9rZU84uH4SUa80noQ==') .then(res => { // 取res.data赋值,而非整个res this.setState({countries: res.data}); }) // Error catching .catch(error => this.setState({ error, isLoading: false })); }
内容的提问来源于stack exchange,提问作者BennKingy
相关产品推荐
相关产品推荐

