我正在练习打字本,我遇到了一个问题,我试图将信息从API传递给一个变量(这只是为了获得必要的信息),但是我有这样的错误消息:‘MyProps’类型上不存在属性'id‘,’MyProps‘类型上不存在属性'url’,这是我的代码。
import { useEffect } from "react";
import { CardGif } from "./components/CardGif";
import { Content } from "./components/layout/Content";
import InterfaceImage from './Interfaces/InterfaceImage'
interface MyProps {
gifs: InterfaceImage[]
}
function App() {
const handleLoadInformation = async () => {
const key = 'url';
const url = `https://api.giphy.com/v1/gifs/search?q=goku&limit=10&api_key=${key}`;
const response = await fetch(url);
const { data } = await response.json();
const images = data.map((img: MyProps) => {
return {
id: img.id,
url: img.url
}
})
}
useEffect(() => {
handleLoadInformation();
}, [])
return (
<div>
<Content>
<div className="w-[90%] m-auto columns-3">
<CardGif />
</div>
</Content>
</div>
);
}
export default App;
这是我的界面:
export default interface InterfaceImage {
id: number,
url: string,
}
发布于 2022-02-20 14:30:14
错误源于以下代码:
const images = data.map((img: MyProps) => {
return {
id: img.id,
url: img.url
}
})
当您尝试获取img.id
和img.url
时,TypeScript编译器会看到img
应该是MyProps
类型的,它只有一个属性-gifs
。
interface MyProps {
gifs: InterfaceImage[] // no `id` or `url` props here
}
要修复此错误,通常可以将支持添加到接口定义中:
interface MyProps {
gifs: InterfaceImage[],
id: number,
url: string,
}
但是,考虑到您定义的InterfaceImage
接口,我假设您真正需要的是更改.map()
回调中的类型注释:
const images = data.map((img: InterfaceImage) => {
return {
id: img.id,
url: img.url
}
})
https://stackoverflow.com/questions/71199327
复制