Issue
I was practicing with typescript and I have a problem, I am trying to pass information from the API to a variable (this is just to have the necessary information), but I have this error message:: "Property ‘id’ does not exist on type ‘MyProps’" and "Property ‘url’ does not exist on type ‘MyProps’", this is my code.
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;
and this is my Interface:
export default interface InterfaceImage {
id: number,
url: string,
}
Solution
The error stems from this piece of code:
const images = data.map((img: MyProps) => {
return {
id: img.id,
url: img.url
}
})
When you try to get img.id
and img.url
, the TypeScript compiler sees that img
should be of type MyProps
, which only has one property—gifs
.
interface MyProps {
gifs: InterfaceImage[] // no `id` or `url` props here
}
To fix this error in general, you can add the props to the interface definition:
interface MyProps {
gifs: InterfaceImage[],
id: number,
url: string,
}
However, considering the InterfaceImage
interface that you have defined, I assume that what you really need is to change the type annotation in the .map()
callback:
const images = data.map((img: InterfaceImage) => {
return {
id: img.id,
url: img.url
}
})
Answered By – Jacob
Answer Checked By – Marilyn (AngularFixing Volunteer)