Home > Software design >  (TS) Types of parameters are incompatible
(TS) Types of parameters are incompatible

Time:07-08

I have this code

  const [data, setData] = useState([] as object[]);

 const dataHandle = ( recipes: object[] ) => {
    setData(  
     recipes.map((recipe: { recipe_id: string, title: string, image_url: string }) => { 
        return {
          id: recipe.recipe_id as string, 
          title: recipe.title as string,
          image: recipe.image_url as string,
        };
      })
    );
  };

and I'm getting this error

Argument of type '(recipe: { recipe_id: string; title: string; image_url: string;}) => { id: string; title: string; image: string; }' is not assignable to parameter of type '(value: object, index: number, array: object[]) => { id: string; title: string; image: string; }'. Types of parameters 'recipe' and 'value' are incompatible. Type '{}' is missing the following properties from type '{ recipe_id: string; title: string; image_url: string; }': recipe_id, title, image_urlts(2345)

Can someone explain what the correct type of recipe is?

CodePudding user response:

Hey I think the problem here is that object[] is too vague to describe the object you want to type so typescript doesn't know if recipe indeed has those fields inside so you can describe this better for typescript like this:

interface IRecipe{
    recipe_id: string;
    title: string;
    image_url: string;
}
const dataHandle: (recipes: IRecipe[]) => void = (recipes) => {
    setData(
        recipes.map((recipe: { recipe_id: string; title: string; image_url: string }) => {
            return {
                id: recipe.recipe_id as string,
                title: recipe.title as string,
                image: recipe.image_url as string,
            };
        })
    );
};

notice that now recipes array has the type IRecipe which describes exactly what the fields of a recipe are. Also notice that I have change a little bit the way you describe the types to specify also the value that the function dataHandle returns (void in this case) if you describe all your functions following that pattern it will be easier to find errors like this. Also if you want to help the people using the functions you implement in the future I recommend you to use pop-up

describing how your function behaves and all the parameters and return types among with all the comments and descriptions you want to include to each parameter to clarify what your function is doing, you just need to hover over your function name and this will appear ;). Hope this help! feel free to ask anything else!

  • Related