Here is the code snippet I am working with:
type Data = {
id: string;
name: string;
description: string;
price: number;
};
const FetchMeals = async (req: NextApiRequest, res: NextApiResponse<Data>) => {
const response = await fetch(
"https://url.com/Meals.json"
);
if (!response.ok) {
throw new Error("Something went wrong");
}
const responseData = await response.json();
const loadedMeals:Data[] = [];
for (const key in responseData) {
loadedMeals.push({
id: key,
name: responseData[key].name,
description: responseData[key].description,
price: responseData[key].price,
});
}
res.status(200).json({ loadedMeals });
};
export default FetchMeals;
I have specified the response body type as an array of Data
by using < >
brackets next to NextApiResponse
. When I define my array as const loadedMeals:Data[] = [];
, I encounter an error "string type is not assignable to type number" at the id where it's defined as a string in the code below:
for (const key in responseData) {
loadedMeals.push({
id: key,
name: responseData[key].name,
description: responseData[key].description,
price: responseData[key].price,
});
}
Question 1) Why does the type of id in the loop become a string?
When I try to return loadedMeals
in
res.status(200).json({ loadedMeals });
, I receive this error message:
Argument of type '{ loadedMeals: Data[]; }' is not assignable to parameter of type 'Data'. Object literal may only specify known properties, and 'loadedMeals' does not exist in type 'Data'.
Question 2) What could be causing this error?
Even though the Postman GET request returns the correct array with values, my IDE shows this error. Is this related to my TypeScript code or just an issue with the IDE? This problem occurs in Next.js API routing, and I'm using VSCode as my IDE.
I've tried looking up solutions but couldn't figure out what I might be doing wrong here.