Axios 强制"any"类型对响应类型



我正试图在typescript react项目中使用Axios获取数据,我将Axios中的响应类型设置为CartItemType,但Axios强制响应类型为CartItemType和any,这破坏了我的代码。为什么它会迫使";任何";类型如何摆脱它?

export type CartItemType = {
id: number;
category: string;
description: string;
image: string;
price: number;
title: string;
amount: number;
};
const App = () => {
const [data, setData] = useState<CartItemType[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
axios.get<CartItemType[]>("https://fakestoreapi.com/products")
.then(products => {
setData(products);
setLoading(false);
})
}, [])

该错误出现在then函数中的products参数处。当我将鼠标悬停在错误上时,它显示:类型为"AxiosResponse<CartItemType[],任意>'不可分配给"SetStateAction<"类型的参数;CartItemType[]>'。键入AxiosResponse<CartItemType[],任意>'不可分配给类型"(prevState:CartItemType[](=>CartItemType[]'。键入AxiosResponse<CartItemType[],任意>'没有为签名"(prevState:CartItemType[](:CartItemType[]"提供匹配项。ts(2345(

为什么会有这个";,任何";类型

axios返回的是响应而不是类型本身,所以它应该是

axios.get<CartItemType[]>("https://fakestoreapi.com/products")
.then(response=> {
setData(response.data); // <-- response.data should be CartItemType[]
setLoading(false);
})

最新更新