如何正确使用TypeScript泛型并解决axios.get调用的类型报错问题
问题原因
该报错和你定义的Location泛型没有关联,是axios.get方法的传参格式使用错误:
axios.get的标准传参规则为:第一个参数必填字符串类型的请求url,第二个参数才是可选的请求配置对象
你当前把包含url、method、headers的完整配置对象直接传给了要求传string类型的第一个入参,因此触发了类型不匹配报错。
修复方案
有两种可选的正确写法:
写法1:保持使用axios.get,调整传参顺序
把url提取出来作为第一个参数,配置对象仅保留headers等额外字段,不需要额外声明method,axios.get方法默认对应get请求:
export interface Location { id: number; address: { houseNumber: string; }; } export const getEuropeLocations = async ( apiKey: string ) => { let response = await axios.get<Location>( `${apiBaseUrl}europe/`, // 第一个参数传url字符串 { headers: { Authorization: `Bearer ${apiKey}`, }, } ); return response.data; };
写法2:使用通用axios请求方法传完整配置
如果你习惯把所有请求配置都放在同一个对象中,可以换成axios()或者axios.request()方法,泛型的定义规则保持不变:
export interface Location { id: number; address: { houseNumber: string; }; } export const getEuropeLocations = async ( apiKey: string ) => { let response = await axios<Location>({ method: "get", url: `${apiBaseUrl}europe/`, headers: { Authorization: `Bearer ${apiKey}`, }, }); return response.data; };
泛型使用补充说明
你此处给axios返回值指定Location泛型的写法是正确的,修复传参问题后,response.data会自动获得Location对应的类型提示,不需要额外调整泛型逻辑。
内容的提问来源于stack exchange,提问作者Puzzle234
相关产品推荐
相关产品推荐

