I understand that I can change extendedIngredients
in my Recipe
Interface to return a string[]
so that it matches the outcome of the API call data and solves the error, but the issue is that when I change
extendedIngredients: [
{
original: string;
}
];
to
extendedIngredients: string[];
I get the issue of 'original' does not exist on type 'string'
. But I need this in order to get this path-specific data from my API call.
useEffect(() => {
const getRecipe = async () => {
try {
const res = await fetch(
`https://api.spoonacular.com/recipes/${id}/information?apiKey=KEY&includeNutrition=false`
);
const data = await res.json();
recipeInfo(data);
// console.log(data);
} catch (err) {
console.error(err);
}
};
getRecipe();
}, [id]);
const recipeInfo = (info: Recipe) => {
const recipeData: Recipe = {
id: info.id,
title: info.title,
image: info.image,
servings: info.servings,
readyInMinutes: info.readyInMinutes,
dairyFree: info.dairyFree,
glutenFree: info.glutenFree,
ketogenic: info.ketogenic,
vegan: info.vegan,
vegetarian: info.vegetarian,
extendedIngredients: info.extendedIngredients.map((ing) => ing.original),
};
console.log(recipeData);
};
I am very new to typescript I am clearly not understanding something, any help?
It's not clear what or where is producing the second error you mention, so it's not clear if you really need to use an array of objects with just one property instead of an array of strings. But...
If you just need this to return an array of objects with just one property:
info.extendedIngredients.map((ing) => ing.original)
Then you would return that object from the .map()
callback:
info.extendedIngredients.map((ing) => ({ original: ing.original }))