I recently started working with TypeScript and am therefore a beginner :D.
For an application, I use the following generic method to fetch JSON objects from different endpoints:
interface UnknownObject {
[index: string]: UnknownObject;
}
const fetchJSON = async (
url: string,
body?: object
): Promise<UnknownObject> => {
try {
let response;
if (!body) {
response = await fetch(url);
} else {
response = await fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(body)
});
}
const data = await response.json();
if (response.status === 404) data.error = 404;
console.log(data);
return data;
} catch (err) {
throw err;
}
};
export default fetchJSON;
I don't quite understand how I should define the interface for that method.
Currently (see code) I basically disabled Typescript with a recursive interface telling "this is an object with possible sub-objects". (I've disabled the type since it is not recommended).
Something that would fix the problem would be the possibility to define the interface as soon as I use the method in the code.
For instance, calling the method to fetch a page object could look like that: fetchJSON("pageurl"): PageProps. Without having to declare an interface when defining the function itself. I didn't find any way to do it though.
Another idea I had is to create different fetch methods based on what endpoint is used. For instance, fetchPageJSON, fetchUserJSON, etc. Like this, I would always know what object should be returned but I would have to write the same method multiple times.
What is the proper way to do this?