I've been researching how to create a TypeScript wrapper for type-safe fetch calls, and I came across a helpful forum thread from 2016. However, despite attempting the suggestions provided in that thread, I am still encountering issues with my code.
The TS Linter is flagging an error when I try to use this code snippet: response.json<T>()
, stating "Expected 0 type arguments, but got 1."
After reading through another forum post, I made adjustments as follows:
data => data as T
Unfortunately, both options above are not working as intended, and they return undefined. When using a source like this one, I expect to be able to specify the structure like so:
api<{ name: string; username: string }>('https://jsonplaceholder.typicode.com/users')
The subsequent clause then should be:
.then(({ name, username })
I would greatly appreciate a detailed guide on creating a wrapper function for performing type-safe fetch calls.
EDIT
As requested, here is a more comprehensive code snippet:
api<T>(url: string): Promise<T> {
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json().then(data => data as T);
})
.catch((error: Error) => {
throw error;
});
}
// consumer
this.api<{ name: string; username: string }>("https://jsonplaceholder.typicode.com/users/")
.then(({ name, username }) => {
console.log(name, username);
})
.catch(error => {
console.error(error);
});