Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generic interfaces in TypeScript
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