Skip to content

Instantly share code, notes, and snippets.

@bennycode
Created May 15, 2022 23:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennycode/b6cfde446dba6732a7ab2b16b2ea4724 to your computer and use it in GitHub Desktop.
Save bennycode/b6cfde446dba6732a7ab2b16b2ea4724 to your computer and use it in GitHub Desktop.
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