Skip to content

Instantly share code, notes, and snippets.

@mikaelvesavuori
Created October 30, 2022 14:58
Show Gist options
  • Save mikaelvesavuori/c7552ae574e9ff8117ac1b811cde5e26 to your computer and use it in GitHub Desktop.
Save mikaelvesavuori/c7552ae574e9ff8117ac1b811cde5e26 to your computer and use it in GitHub Desktop.
Basic example of a generic type in TypeScript.
// See: https://www.digitalocean.com/community/tutorials/how-to-use-generics-in-typescript
type StarWarsApiResponse = {
name: string;
rotation_period: string;
orbital_period: string;
diameter: string;
climate: string;
gravity: string;
terrain: string;
surface_water: string;
population: string;
residents: string[];
films: string[];
created: string;
edited: string;
url: string;
};
async function fetchApi<ResultType>(path: string): Promise<ResultType> {
const response = await fetch(`https://swapi.dev/api/${path}`);
return response.json();
}
async function run() {
const response = await fetchApi<StarWarsApiResponse>('planets/3');
console.log(response);
}
run();
export { };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment