Created
May 15, 2022 23:00
-
-
Save bennycode/b6cfde446dba6732a7ab2b16b2ea4724 to your computer and use it in GitHub Desktop.
Generic interfaces in TypeScript
This file contains 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 HttpResponse<T> { | |
code: number; | |
data: T; | |
} | |
interface ResponseData { | |
completed: boolean; | |
id: number; | |
title: string; | |
userId: number; | |
} | |
async function getJson<T>(url: string): Promise<HttpResponse<T>> { | |
const response = await fetch(url); | |
const data: T = await response.json(); | |
return { | |
code: response.status, | |
data, | |
}; | |
} | |
(async () => { | |
const response = await getJson<ResponseData>('https://jsonplaceholder.typicode.com/todos/1'); | |
console.log(response.code, response.data.title); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment