I have the following code
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 defined the type of body of the response as the type above, and defined the type with < > brackets next to NextApiResponse. The type of the body should be an array of Data. I've got two questions here. If I define my array with the type Data like const loadedMeals:Data[] = []; at the id 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, }); } I'm getting an error "string type is not assignable to type number".
Question 1) How come the type of id in the for loop becomes string?
At loadedMeals in res.status(200).json({ loadedMeals }); it's showing this error
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) Why is it showing this error?
When I do a postman GET request it's returning the correct array with the values but IDE shows this error. Is it just something to do with IDE or is my TypeScript code wrong that I should be adding something to my code. This is Next.js API routing and the IDE I'm using is VSCode.
I did look up answers but couldn't understand what I'm doing wrong here.
responseDatato the console, what's the output?resobject asres: NextApiResponse<{ loadedMeals: Data[] }>to match what you're returning in the response.