Created
January 27, 2019 10:57
-
-
Save carlrip/dd98f8d080b8f154e18291651b733ae3 to your computer and use it in GitHub Desktop.
async fetch with types returning full response
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
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