Created
August 16, 2020 10:49
-
-
Save leolanese/191c7d0cdd1d220276d06dceea4313e6 to your computer and use it in GitHub Desktop.
fetch API + async-await + TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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