Skip to content

Instantly share code, notes, and snippets.

@carlrip
Created January 27, 2019 10:57
Show Gist options
  • Save carlrip/dd98f8d080b8f154e18291651b733ae3 to your computer and use it in GitHub Desktop.
Save carlrip/dd98f8d080b8f154e18291651b733ae3 to your computer and use it in GitHub Desktop.
async fetch with types returning full response
interface IHttpResponse<T> extends Response {
parsedBody?: T;
}
export const http = <T>(request: RequestInfo): Promise<IHttpResponse<T>> => {
let response: IHttpResponse<T>;
return new Promise(resolve => {
fetch(request)
.then(res => {
response = res;
return res.json();
})
.then(body => {
response.parsedBody = body;
resolve(response);
});
});
};
// example consuming code
interface ITodo {
userId: number;
id: number;
title: string;
completed: boolean;
}
const response = await http<ITodo[]>(
"https://jsonplaceholder.typicode.com/todos"
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment