Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
fetch API + async-await + TypeScript
// declaring fetch + async-await + TypeScript
export async function get<T>(
path: string,
args: RequestInit = { method: "get" }
): Promise<HttpResponse<T>> {
return await http<T>(new Request(path, args));
};
export async function post<T>(
path: string,
body: any,
args: RequestInit = { method: "post", body: JSON.stringify(body) }
): Promise<HttpResponse<T>> {
return await http<T>(new Request(path, args));
};
export async function put<T>(
path: string,
body: any,
args: RequestInit = { method: "put", body: JSON.stringify(body) }
): Promise<HttpResponse<T>> {
return await http<T>(new Request(path, args));
};
...
// example consuming code
const response = await post<{ id: number }>(
"https://jsonplaceholder.typicode.com/posts",
{ title: "my post", body: "some content" }
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment