Could you assist me in grasping the workings of TypeScript? I am currently trying to learn it but am struggling with understanding certain behaviors.
Example 1: The issue lies in the type errors not being detected, please refer to the commented message within the code.
"use client";
import axios from "axios";
import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
type Recipe = {
title: number; ///// TITLE SHOULD BE A STRING, NOT A NUMBER ////
image: string;
};
export default function Categories() {
const { category } = useParams();
const [recipes, setRecipes] = useState<Recipe[]>([]); //////USING TYPE RECIPE/////
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get<Recipe[]>( /////USING THE SAME TYPE RECIPE /////
`https://mealtime-dkgl.onrender.com/api/recipes/${category}`
);
const extractedRecipes = response.data.map((recipe) => ({
title: recipe.title,
image: recipe.image,
}));
setRecipes(extractedRecipes); /////// NO ERRORS DETECTED ///////
} catch (error) {
console.error("Error fetching recipes", error);
}
};
fetchData();
}, [category]);
console.log(recipes);
return <main></main>;
}
Example 2: It appears to be functioning as expected.
"use client";
import axios from "axios";
import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
type Recipe = {
title: string;
image: string;
};
type RecipeResponse = {
title: number; ////// ERROR OCCURS HERE /////////
image: string;
};
export default function categories() {
const { category } = useParams();
const [recipes, setRecipes] = useState<Recipe[]>([]); /////// USING TYPE RECIPE //////
useEffect(() => {
const fetchData = async () => {
const response = await axios.get<RecipeResponse[]>( //// UTILIZING TYPE RECIPE RESPONSE /////
`https://mealtime-dkgl.onrender.com/api/recipes/${category}`
);
const extractedRecipes = response.data.map((recipe) => ({
title: recipe.title,
image: recipe.image,
}));
setRecipes(extractedRecipes); /////ERROR DETECTED/////
};
fetchData();
}, [category]);
return <main></main>;
}
I trust that my examples are clear enough. In essence, I have observed that re-using "type Recipe" multiple times in my code leads to undetected errors.