Created
January 27, 2019 10:54
-
-
Save carlrip/a966c175d1a7e9f61a8f46fc5e48dc8b to your computer and use it in GitHub Desktop.
async fetch with types
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
export const http = <T>(request: RequestInfo): Promise<T> => { | |
return new Promise((resolve) => { | |
fetch(request) | |
.then(response => response.json()) | |
.then(body => { | |
resolve(body); | |
}); | |
}); | |
}; | |
// example consuming code | |
interface ITodo { | |
userId: number; | |
id: number; | |
title: string; | |
completed: boolean; | |
} | |
const data = 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